Windows PowerShell Language Quick Reference
Windows PowerShell Language Quick Reference
Native Support for Different Type Systems |
||||||||||||||||||||||||||||||||
Windows PowerShell adapts WMI, XML, ASDI, Example |
||||||||||||||||||||||||||||||||
Arithmetic Binary Operators |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Array Operations |
||||||||||||||||||||||||||||||||
Does this array have a 1,2,3,5,3,2 –contains 3
1,2,3,5,3,2 –eq 3 Return all elements less than 3: 1,2,3,5,3,2 –lt 3 Test if 2 exists in collection: if (1, 3, 5 –contains 2) … Other operators: -gt, -le, -ge, -ne |
||||||||||||||||||||||||||||||||
Arrays |
||||||||||||||||||||||||||||||||
· Arrays are zero based. |
||||||||||||||||||||||||||||||||
Assignment Operators |
||||||||||||||||||||||||||||||||
=, +=, -=, *=, /=, %= |
||||||||||||||||||||||||||||||||
Associative Arrays (Hashtables) |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Boolean Values and Operators |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Break (Scripting) |
||||||||||||||||||||||||||||||||
The break commands exits a loop. It can take an optional LABEL to break to Example: while (1) { $a = something if ($a –eq 1) break; } |
||||||||||||||||||||||||||||||||
Command Expansion Operators |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Comments |
||||||||||||||||||||||||||||||||
# This is a comment because # is the first char of a token $a = “#This is not a comment…” $a = “something” # …but this is. Write-Host Hello#world |
||||||||||||||||||||||||||||||||
Comparison Operators |
||||||||||||||||||||||||||||||||
“i” or “c” may be prepended to get case-insensitive or case-sensitive operations (for example, –ceq ) |
||||||||||||||||||||||||||||||||
Continue (Scripting) |
||||||||||||||||||||||||||||||||
The continue statement continues the next iteration of a loop without breaking out of it. Example: while (1) { $a = something if ($a –eq 1) (continue) # This line is not reached unless $a == 1 } # This line is never reached. |
||||||||||||||||||||||||||||||||
Dot Sourcing |
||||||||||||||||||||||||||||||||
Dot sourcing allows running functions, script blocks, and scripts in the current scope rather than a local one. Example: . MyFunction If MyFunction sets a variable, it is set in the current scope rather than the function’s local scope. $a = {$x = Get-Process | Select –First 2} . $a #Evaluates the script block in the current scope |
||||||||||||||||||||||||||||||||
Escape Sequences |
||||||||||||||||||||||||||||||||
The Windows PowerShell escape character is the backwards apostrophe, or `. To make a character literal, precede it with `. To specify a ` use ``.
|
||||||||||||||||||||||||||||||||
Execution Order |
||||||||||||||||||||||||||||||||
Windows PowerShell attempts to resolve commands in the following order: aliases, functions, cmdlets, scripts, executables, and normal files. |
||||||||||||||||||||||||||||||||
For (Scripting) |
||||||||||||||||||||||||||||||||
[:label] for ([initializer]; [condition]; [iterator]) {} Example: for ($i = 0; $i –lt 5; $i++) {Write-Object $i} |
||||||||||||||||||||||||||||||||
Foreach (Scripting) |
||||||||||||||||||||||||||||||||
[:label] foreach (identifier in collection) {} Expression | foreach {} Expression | foreach {BEGIN{} PROCESS{} END{}} Examples: $i = 1,2,3 foreach ($z in $i) {Write-Object $z} Get-Process |foreach {BEGIN{$x=1} PROCESS{$X++} END{“$X Processes”}} |
||||||||||||||||||||||||||||||||
Functions (Scripting) |
||||||||||||||||||||||||||||||||
function MyFunction { write-object $args[0] } function test ([string]$label=”default label”,[int]$start=0) { BEGIN {$x=$start} PROCESS {“$label: $_”’; $x++} END{“$x total”} } |
||||||||||||||||||||||||||||||||
Filters (Scripting) |
||||||||||||||||||||||||||||||||
Filters are a shorthand way of writing a function with a PROCESS script block. filter MyFilter { $_.name } |
||||||||||||||||||||||||||||||||
If/elseif/else (Scripting) |
||||||||||||||||||||||||||||||||
if (condition) {…} elseif (condition) {…} else {…} On the command line, the closing brace must be on the same line as elseif and else. This restriction does not apply to scripts |
||||||||||||||||||||||||||||||||
Invoke Operator |
||||||||||||||||||||||||||||||||
The & operator can be used to invoke a script block or the name of a command or function. Example: $a = “Get-Process” &$a $a = { Get-Process | Select -First 2 } &$a |
||||||||||||||||||||||||||||||||
Logical Operators |
||||||||||||||||||||||||||||||||
!, -not, -and, -or |
||||||||||||||||||||||||||||||||
Method Calls |
||||||||||||||||||||||||||||||||
Methods can be called on objects. Examples: $a = “This is a string” $a.ToUpper() $a.SubString(0,3) $a.SubString(0,($a.length/2)) $a.Substring(($a.length/2), ($a.length/3)) Static Methods are callable with the “::” operator [DateTime]::IsLeapYear(2005) |
||||||||||||||||||||||||||||||||
Windows PowerShell Automatic Variables (Not Exhaustive) |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Object Properties |
||||||||||||||||||||||||||||||||
An object’s properties can be referenced directly with the “.” operator. $a = Get-Date $a.Date $a.TimeOfDay.Hours Static properties can be referenced with the “::” operator [DateTime]::Now |
||||||||||||||||||||||||||||||||
Operator Precedence |
||||||||||||||||||||||||||||||||
In Windows PowerShell, operators are evaluated in the following precedence: () {}, @ $, !, [ ], ., &, ++ --, Unary + -, * / %, Binary + -, Comparison Operators, -and –or, |, > >>, = |
||||||||||||||||||||||||||||||||
Other Operators |
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
Return (Scripting) |
||||||||||||||||||||||||||||||||
The return command exits the current script or function and returns a value. Example: function foo { return 1 } |
||||||||||||||||||||||||||||||||
Scopes (Scripting) |
||||||||||||||||||||||||||||||||
Variables and other data elements may be instantiated in different scopes: · Variables in the global scope are visible in all scopes. · Variables in the script scope are visible to all scopes within that script file. · Variables in the local scope are visible only in the current scope and its children. · Private scope variables are visible only to that current scope. A scope is created in the body of a shell function (see function creation) Example: $global:a = 4 $script:a = 5 $local:a = 3 $private:a = 6 |
||||||||||||||||||||||||||||||||
Script Blocks |
||||||||||||||||||||||||||||||||
Commands and expressions can be stored in a script block object and executed later. Example: $block = {Get-Process; $a=1} &$block |
||||||||||||||||||||||||||||||||
Scripts |
||||||||||||||||||||||||||||||||
Windows PowerShell commands can be stored in and executed from script files. The file extension for Windows PowerShell scripts is “.ps1”. Parameters can be passed to a script and a script can return a value. Example: $sum = MyAdder.ps1 1 2 3 |
||||||||||||||||||||||||||||||||
Strings |
||||||||||||||||||||||||||||||||
String constants: “this is a string, this $variable is expanded as is $(2+2)” ‘this is a string, this $variable is not expanded’ @” This is a “here string” which can contain anything including carriage returns and quotes. Exressions $(2+2) are evaluated ”@ @’ “here string” with single quotes do not evaluate expressions. ‘@
|
||||||||||||||||||||||||||||||||
Switch (Scripting) |
||||||||||||||||||||||||||||||||
The variable $_ is available in the script. $_ represents the current value being evaluated. If an array is used in switch, each element of the array is tested. Example: $var = "word1","word2","word3" switch -regex ($var) { "word1" {"Multi-match Exact " + $_ } "word2" {"Multi-match Exact " + $_ } "w.*2" {"Pattern match Exact " + $_ } default {"Multi-match Default " + $_ } } Output: Multi-match Exact word1 Multi-match Exact word2 Pattern match Exact word2 Multi-match Default word3 |
||||||||||||||||||||||||||||||||
Throw |
||||||||||||||||||||||||||||||||
Throw provides the same functionality for scripts as the ThrowTerminatingError API does for cmdlets. throw "Danger, Danger" Danger, Danger At line:1 char:6 + throw <<<< "Danger, Danger" Throw takes a string, exception, or ErrorRecord as an argument. |
||||||||||||||||||||||||||||||||
Traps |
||||||||||||||||||||||||||||||||
Trap [ExceptionType] { if (…) { continue # continue at the script statement after the one that cased the # trap; $? is updated but no error record is generated } else (…) { Break # rethrow the exception } # Doing nothing will do what is specified in the # $ErrorActionPreference setting } |
||||||||||||||||||||||||||||||||
Type Operations (Scripting) |
||||||||||||||||||||||||||||||||
-is IS type (e.g. $a -is [int] ) -as convert to type (e.g. 1 -as [string] treats 1 as a string ) |
||||||||||||||||||||||||||||||||
Until (Scripting) |
||||||||||||||||||||||||||||||||
do { … } until (condition) |
||||||||||||||||||||||||||||||||
Variables |
||||||||||||||||||||||||||||||||
Format: $[scope:]name or ${anyname} or ${any path} Examples: $a = 1 ${!@#$%^&*()}=3 $global:a = 1 # Visible everywhere $local:a = 1 # defined in this scope and visible to children $private:a=1 # same as local but invisible to child scopes $script:a=1 # visible to everything in this script $env:path = “d:\windows” ${C:\TEMP\testfile.txt}=”This writes to a file” Get-Variable –scope Get-Variable –scope |
||||||||||||||||||||||||||||||||
While (Scripting) |
||||||||||||||||||||||||||||||||
[:label] while (condition) { … } do { … } while (condition) |
||||||||||||||||||||||||||||||||
Parsing |
||||||||||||||||||||||||||||||||
Windows PowerShell parses in two modes—command mode and expression mode. In expression mode, Windows PowerShell parses as most high-level languages parse: numbers are numbers; strings need to be quoted, and so on. Expressions are things such as: 2+2 4 "Hello" + " world" Hello world $a = "hi" $a.length * 13 26 When parsing in command mode, strings do not need to be quoted and everything is treated like a string except variables and things in parentheses. For example: copy users.txt accounts.txt users.txt and accounts.txt are treated as strings write-host 2+2 2+2 is treated as string, not an expression to evaluate copy $src $dest $src and $dest are variables. Not needing to use quotation marks when working in a command shell can be very beneficial in the long run because it greatly reduces the amount of typing required. The parsing mode is determined by the first token encountered. If the token is a number, variable, or quoted string, then the shell parses in expression mode. If the line starts with a letter, an & (ampersand), or a . (dot) followed by a space or a letter, the parsing is done in command mode.
It is very useful to be able to mix expressions and commands; which you can do by using parentheses. Inside parentheses, the mode discovery process starts over. Write-Host (2+2) 2+2 is treated as an expression to evaluate and is passed to the Write-Host command. (Get-Date).day + 2 Get-Date is treated as a command, and the result of executing it becomes the left value in the expression. You can nest commands and expressions without restrictions. Write-Host ((Get-Date).day + 2) Get-Date is a command. ((Get-Date).day+2) is an expression, and Write-Host ((Get-Date).day + 2) is a command again. Write-Host ((Get-Date) - (Get-Date).date) The Get-Date command is used twice to determine how much time has passed since midnight (condition). |