You are on page 1of 4

Windows PowerShell 3.

0 Language Quick Reference


Created by http://powershellmagazine.com

Useful Commands Bitwise Operators , Comma operator (Array


-band Bitwise AND constructor)
Update-Help Downloads and installs newest help -bor Bitwise OR (inclusive) . Dot-sourcing operator runs a
files -bxor Bitwise OR (exclusive) script in the current scope
Get-Help Displays information about -bnot Bitwise NOT . c:\scripts\sample.ps1
commands and concepts -shl, -shr Bitwise shift operators. Bit
Get-Command Gets all commands shift left, bit shift right $( ) Subexpression operator
Get-Member Gets the properties and methods (arithmetic for signed, @( ) Array subexpression operator
of objects logical for unsigned values) & The call operator, also known as
Get-Module Gets the modules that have been the "invocation operator," lets
imported or that can be imported Other Operators you run commands that are
into the current session -Split Splits a string stored in variables and
“abcdefghi” -split “de” represented by strings.
Operators $a = "Get-Process"
-join Joins multiple strings & $a
Assignment Operators $sb = { Get-Process | Select –First 2 }
“abc”,”def”,”ghi” -join “;”
=, +=, -=, *=, /=, %=, ++, -- Assigns one or more values & $sb
to a variable
.. Range operator Logical Operators
1..10 | foreach {$_ * 5} -and, -or, -xor, -not, ! Connect expressions and
Comparison Operators
-eq, -ne Equal, not equal statements, allowing you to test
-is, -isnot Type evaluator (Boolean). for multiple conditions
-gt, -ge Greater than, greater than
Tells whether an object is an Redirection Operators
or equal to
instance of a specified .NET >, >> The redirection operators enable
-lt, -le Less than, less than or
Framework type. you to send particular types of
equal to
42 –is [int] output (success, error, warning,
-replace changes the specified
elements of a value verbose, and debug) to files and
-as Type convertor. Tries to to the success output stream.
“abcde” -replace “bc”, “TEST”
convert the input object to Output streams * All output
the specified .NET 1 Success output
-match, -notmatch Regular expression match
Framework type. 2 Errors
-like, -notlike Wildcard matching
$a = 42 –as [String] 3 Warning messages
-contains, -notcontains Returns TRUE if the scalar
value on its right is 4 Verbose output
-f Formats strings by using the 5 Debug messages
contained in the array on
format method of string # Writes warning output to warning.txt
its left
objects Do-Something 3> warning.txt
1,2,3,4,5 -contains 3
1..10 | foreach { "{0:N2}" -f $_ } # Appends verbose.txt with the verbose output
-in, -notin Returns TRUE only when Do-Something 4>> verbose.txt
[] Cast operator. Converts or # Writes debug output to the output stream
test value exactly matches
limits objects to the Do-Something 5>&1
at least one of the
specified type # Redirects all streams to out.txt
reference values.
[datetime]$birthday = "1/10/66" Do-Something *> out.txt
“Windows”-in “Windows”,”PowerShell”
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Arrays $hash.key1 Returns value of key1 $a.Substring(0,3)


$hash["key1"] Returns value of key1 $a | Get-Member -MemberType Method -Static
"a", "b", "c" Array of strings $hash.GetEnumerator | sort Key Sorts a hash table by
1,2,3 Array of integers the Key property Static methods are callable with the "::" operator.
@() Empty array [pscustomobject]@{x=1; y=2} Creates a custom
@(2) Array of one element object [DateTime]::IsLeapYear(2012)
1,(2,3),4 Array within array
,"hi" Array of one element Comments Strings
$arr[5] Sixth element of array*
$arr[2..20] Returns elements 3 thru 21 # This is a comment because # is the first character of a "This is a string, this $variable is expanded as is $(2+2)"
$arr[-1] Returns the last array token ‘This is a string, this $variable is not expanded”
element
$arr[-3..-1] Displays the last three $a = "#This is not a comment…" @"
elements of the array $a = "something" # …but this is. This is a here-string which can contain anything including
$arr[1,4+6..9] Displays the elements at carriage returns and quotes. Expressions are evaluated:
index positions 1,4, and 6 Write-Host Hello#world $(2+2*5). Note that the end marker of the here-string must
through 9 be at the beginning of a line!
@(Get-Process) Forces the result to an Block Comments "@
array using the array sub-
expression operator <# This is @'
$arr=1..10 A multi-line comment #> Here-strings with single quotes do not evaluate expressions:
$arr[($arr.length-1)..0] Reverses an array $(2+2*5)
$arr[1] += 200 Adds to an existing value of Object Properties '@
the second array item
An object’s properties can be referenced directly with the Variables
(increases the value of the
"." operator.
element) Format: $[scope:]name or ${anyname} or ${any path}
$b = $arr[0,1 + 3..6] Creates a new array based $a = Get-Date
on selected elements of an $a | Get-Member –MemberType Property $path = "C:\Windows\System32"
existing array $a.Date Get-ChildItem ${env:ProgramFiles(x86)}
$z = $arr + $b Combines two arrays into a $a.TimeOfDay.Hours $processes = Get-Process
single array, use the plus $a | Get-Member -MemberType Property –Static
operator (+) $global:a =1 # visible everywhere
Static properties can be referenced with the "::" operator. $local:a = 1 # defined in this scope and visible to children
*Arrays are zero-based $private:a = 1 # same as local but invisible to child scopes
[DateTime]::Now $script:a = 1 # visible to everything is this script
Associative Arrays (Hash tables) # Using scope indicates a local variable in remote commands
Methods and with Start-Job
$hash = @{} Creates empty hash table
$localVar = Read-Host "Directory, please"
@{foo=1; bar='value2'} Creates and initialize a
Methods can be called on objects. Invoke-Command -ComputerName localhost -ScriptBlock {
hash table
dir $using:localVar }
[ordered]@{a=1; b=2; c=3}Creates an ordered $a = "This is a string" Start-Job { dir $using:localVar -Recurse}
dictionary $a | Get-Member –MemberType Method $env:Path += ";D:\Scripts"
$hash.key1 = 1 Assigns 1 to key key1 $a.ToUpper()
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Get-Command -Noun Variable # the Variable Cmdlets $Host Reference to the application hosting the $OFS Output Field Separator. Specifies
Get-ChildItem variable: # listing all variables using the POWERSHELL language the character that separates the
variable drive $Input Enumerator of objects piped to a script elements of an array when the
$LastExitCode Exit code of last program or script array is converted to a string. The
# strongly-typed variable (can contain only integers) $Matches Exit code of last program or script default value is: Space.
[int]$number=8 $MyInvocation An object with information about the $OutputEncoding Determines the character
current command encoding method that Windows
# attributes can be used on variables $PSHome The installation location of Windows PowerShell uses when it sends
[ValidateRange(1,10)][int]$number = 1 PowerShell text to other applications
$number = 11 #returns an error $profile The standard profile (may not be $PSDefaultParameterValues Specifies default values for the
present) parameters of cmdlets and
# flip variables $Switch Enumerator in a switch statement advanced functions
$a=1;$b=2 $True Boolean value for TRUE $PSEmailServer Specifies the default e-mail server
$a,$b = $b,$a $False Boolean value for FALSE that is used to send e-mail
$PSCulture Current culture messages
# multi assignment $PSUICulture Current UI culture $PSModuleAutoLoadingPreference Enables and disables
$a,$b,$c = 0 $PsVersionTable Details about the version of Windows automatic importing of modules
$a,$b,$c = 'a','b','c' PowerShell in the session. "All" is the default.
$a,$b,$c = 'a b c'.split() $Pwd The full path of the current directory $PSSessionApplicationName Specifies the default application
name for a remote command that
# create read only variable (can be overwritten with - Windows PowerShell Preference Variables uses WS-Management technology
Force) $PSSessionConfigurationName Specifies the default session
Set-Variable -Name ReadOnlyVar -Value 3 -Option $ConfirmPreference Determines whether Windows configuration that is used for
ReadOnly PowerShell automatically PSSessions created in the current
prompts you for confirmation session
# create Constant variable (cannot be overwritten) before running a cmdlet or $PSSessionOption Establishes the default values for
Set-Variable -Name Pi -Value 3.14 -Option Constant function advanced user options in a
$DebugPreference Determines how Windows remote session
Windows PowerShell Automatic Variables PowerShell responds to
(not exhaustive) $VerbosePreference Determines how Windows
debugging PowerShell responds to verbose
$$ Last token of the previous $ErrorActionPreference Determines how Windows messages generated by a script,
command line PowerShell responds to a non- cmdlet or provider
$? Boolean status of last command terminating error $WarningPreference Determines how Windows
$^ First token of the previous $ErrorView Determines the display format PowerShell responds to warning
command line of error messages in Windows messages generated by a script,
$_, $PSItem Current pipeline object PowerShell cmdlet or provider
$Args Arguments to a script or function $FormatEnumerationLimitDetermines how many $WhatIfPreference Determines whether WhatIf is
$Error Array of errors from previous enumerated items are included automatically enabled for every
commands in a display command that supports it
$ForEach Reference to the enumerator in a $MaximumHistoryCount Determines how many
foreach loop commands are saved in the
$Home The user’s home directory command history for the
current session
Windows PowerShell 3.0 Language Quick Reference
Created by http://powershellmagazine.com

Windows PowerShell Learning Resources The PowerShell Community Toolbar


http://powershell.ourtoolbar.com/
Microsoft Resources
irc.freenode.net #PowerShell
Microsoft Windows PowerShell
http://www.microsoft.com/powershell
Free eBooks and Guides
Windows PowerShell Team Blog
http://blogs.msdn.com/PowerShell Mastering PowerShell, Second Edition - Dr. Tobias Weltner
http://powershell.com/cs/blogs/ebookv2/default.aspx
MS TechNet Script Center
http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx Secrets of PowerShell Remoting - Don Jones and Dr. Tobias Weltner
http://powershellbooks.com
PowerShell Forum
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/ Administrator's Guide to Windows PowerShell Remoting
Dr. Tobias Weltner, Aleksandar Nikolic, Richard Giles
Hey, Scripting Guy! Blog http://powershell.com/cs/media/p/4908.aspx
http://blogs.technet.com/b/heyscriptingguy/
Layman's Guide to PowerShell 2.0 Remoting - Ravikanth Chaganti
Windows PowerShell Survival Guide http://www.ravichaganti.com/blog/?page_id=1301
http://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell-
survival-guide-en-us.aspx WMI Query Language via PowerShell - Ravikanth Chaganti
http://www.ravichaganti.com/blog/?page_id=2134
Community Resources
PowerShell 2.0 One Cmdlet at a Time - Jonathan Medd
PowerShell Community http://www.jonathanmedd.net/2010/09/powershell-2-0-one-cmdlet-at-a-time-available-
http://powershellcommunity.org as-pdf-download.html

PowerShell Code Repository Effective Windows PowerShell - Keith Hill


http://poshcode.org http://rkeithhill.wordpress.com/2009/03/08/effective-windows-powershell-the-free-
ebook/
PowerShell.com Community
http://powershell.com

PowerGUI.org Community Books


http://powergui.org
Don Jones, Learn Windows PowerShell in a Month of Lunches
PowerShell Community Groups
Bruce Payette, Windows PowerShell in Action, Second Edition
http://powershellgroup.org
Lee Holmes, Windows PowerShell Cookbook, Second Edition
PowerShell Magazine
http://powershellmagazine.com

You might also like