Windows Powershell Language Quick Reference: Example
Windows Powershell Language Quick Reference: Example
PowerShell
Array of length > 1 while (1)
@(2) Array of length 0 { $a = something
array of 1 element if ($a –eq 1) (continue)
Language Quick
Array of length 1 whose element is TRUE # This line is not reached unless $a == 1
1,(2,3),4 Array of length 1 whose element is FALSE }
array within array # This line is never reached.
Reference
A reference to any object Dot Sourcing
,”hi” Null Dot sourcing allows running functions, script blocks, and
Array of one element scripts in the current scope rather than a local one. Example:
. MyFunction
Native Support for Different Type Systems $a[5] Break (Scripting)
Windows PowerShell adapts WMI, XML, ASDI, ADO, and sixth element of array* The break commands exits a loop. It can take an optional If MyFunction sets a variable, it is set in the current scope
COM objects to provide a common syntax to access their LABEL to break to rather than the function’s local scope.
properties and methods. $a[2][3] Example: $a = {$x = Get-Process | Select –First 2}
Example fourth element or the third while (1) . $a #Evaluates the script block in the current scope
$g = Get-WmiObject Win32_Process { $a = something
$g[0].Name # instead of $g[0].Properties[“Name”] if ($a –eq 1) break; Escape Sequences
element of an array } The Windows PowerShell escape character is the backwards
Arithmetic Binary Operators apostrophe, or `. To make a character literal, precede it with `.
+ $a[2..20] Command Expansion Operators To specify a ` use ``.
addition, concatenation Return elements 3 thru 21 $( ) Special escape sequences
Returns null
- • Arrays are zero based. `0
Subtraction $(1,2,3) (null)
Assignment Operators Returns an array containing1,2,3.
* `a
=, +=, -=, *=, /=, %=
multiplication, string repetition $(Get-Alias a*) (alert)
Returns evaluation of the expression
/ `b
Associative Arrays (Hashtables)
Division @(Get-Alias;Get-Process) (backspace)
$hash = @{ }
Create empty hashtable Executes the two commands and returns the results in an array
% `f
Modulus (form feed)
$h =@{foo=1;bar=2}
Create and initialize a hashtable Comments
# This is a comment because # is the first char of a token `n
$hash.key1 = 1 $a = “#This is not a comment…” (new line)
Array Operations $a = “something” # …but this is.
Assign 1 to key “key1”
Does this array have a 3 in it Write-Host Hello#world `r
1,2,3,5,3,2 –contains 3 (carriage return)
$hash.key1
Returns value of key1 Comparison Operators
Return all elements equal to 3: -eq `t
1,2,3,5,3,2 –eq 3 Equal (tab)
$hash["key1"]
Returns value of key1
Return all elements less than 3: -ne `v
1,2,3,5,3,2 –lt 3 Not equal (vertical quote)
Boolean Values and Operators
Test if 2 exists in collection: -gt –ge
TRUE
if (1, 3, 5 –contains 2) … Greater than, greater than or equal to
FALSE
Other operators: -gt, -le, -ge, -ne Execution Order
$TRUE -lt –le Windows PowerShell attempts to resolve commands in the
Arrays Less than, less than or equal to following order: aliases, functions, cmdlets, scripts,
$FALSE
“a”,“b”,”c” executables, and normal files.
array of strings
Any string of length > 0 except the word “false”
Empty string or the string “false” “i” or “c” may be prepended to get case-insensitive or case- For (Scripting)
1,2,3 sensitive operations (for example, –ceq ) [:label] for ([initializer]; [condition]; [iterator]) {}
array of integers
An object’s properties can be referenced directly with the “.” current scope and its children.
Example: Static Methods are callable with the “::” operator operator. • Private scope variables are visible only to that
for ($i = 0; $i –lt 5; $i++) {Write-Object $i} [DateTime]::IsLeapYear(2005) $a = Get-Date current scope.
$a.Date A scope is created in the body of a shell function (see function
Foreach (Scripting) Windows PowerShell Automatic Variables (Not Exhaustive) $a.TimeOfDay.Hours creation)
[:label] $$ Static properties can be referenced with the “::” operator
foreach (identifier in collection) {} Last token of the previous command line [DateTime]::Now Example:
Expression | foreach {} $global:a = 4
Expression | foreach {BEGIN{} PROCESS{} END{}} $? $script:a = 5
Boolean status of last command Operator Precedence $local:a = 3
Examples: In Windows PowerShell, operators are evaluated in the $private:a = 6
$i = 1,2,3 $^ following precedence: () {}, @ $, !, [ ], ., &, ++ --, Unary + -,
foreach ($z in $i) {Write-Object $z} First token of the previous command line * / %, Binary + -, Comparison Operators, -and –or, |, > >>, =
Get-Process |foreach {BEGIN{$x=1} Script Blocks
PROCESS{$X++} $_ Commands and expressions can be stored in a script block
END{“$X Processes”}} Current pipeline object Other Operators object and executed later.
Example:
Functions (Scripting) $Args ,
function MyFunction { Arguments to a script or function Array constructor $block = {Get-Process; $a=1}
write-object $args[0] &$block
} $Error .. Scripts
Array of errors from previous commands Range operator Windows PowerShell commands can be stored in and executed
function test ([string]$label=”default label”,[int]$start=0) from script files. The file extension for Windows PowerShell
{ BEGIN {$x=$start} PROCESS {“$label: $_”’; $x++} $Foreach -contains scripts is “.ps1”. Parameters can be passed to a script and a
END{“$x total”} Reference to the enumerator in a foreach loop script can return a value.
} Example:
Filters (Scripting) $Home -is $sum = MyAdder.ps1 1 2 3
Filters are a shorthand way of writing a function with a The user’s home directory; usually set to Type evaluator
PROCESS script block. %HOMEDRIVE%\%HOMEPATH% Strings
filter MyFilter { -as String constants:
$_.name $Host Type convertor “this is a string, this $variable is expanded as is $(2+2)”
} Reference to the application hosting the POWERSHELL ‘this is a string, this $variable is not expanded’
If/elseif/else (Scripting) language -band @”
if (condition) {…} Binary and This is a “here string” which can contain anything including
elseif (condition) {…} $Input carriage returns and quotes. Exressions $(2+2) are evaluated
else {…} Enumerator of objects piped to a script -bor ”@
Binary or @’
On the command line, the closing brace must be on the same $LastExitCode “here string” with single quotes do not evaluate expressions.
line as elseif and else. This restriction does not apply to scripts Exit code of last program or script -bnot ‘@
Invoke Operator Binary not
The & operator can be used to invoke a script block or the $Matches String operators
name of a command or function. Hash table of matches found with the –match operator
Example: Return (Scripting) +
$a = “Get-Process” $PSHome The return command exits the current script or function and Concatenate two strings
&$a The installation location of Windows PowerShell returns a value.
$a = { Get-Process | Select -First 2 } Example: *
&$a $profile function foo { Repeat a string some number of times
The standard profile (may not be present) return 1
Logical Operators } -f
!, -not, -and, -or $StackTrace Format a string (.NET format specifiers)
Last exception caught by Windows PowerShell Scopes (Scripting)
Method Calls Variables and other data elements may be instantiated in -replace
Methods can be called on objects. Examples: $Switch different scopes: Replace operator
$a = “This is a string” Enumerator in a switch statement • Variables in the global scope are visible in all "abcd" –replace “bc”, “TEST”
$a.ToUpper() scopes. aTESTd
$a.SubString(0,3) • Variables in the script scope are visible to all
$a.SubString(0,($a.length/2)) Object Properties scopes within that script file. -match
$a.Substring(($a.length/2), ($a.length/3)) • Variables in the local scope are visible only in the Regular expression match
{ in the long run because it greatly reduces the amount of typing
-like … required.
Wildcard matching } until (condition) 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,
Variables an & (ampersand), or a . (dot) followed by a space or a letter,
Switch (Scripting) Format: the parsing is done in command mode.
The variable $_ is available in the script. $_ represents the $[scope:]name or ${anyname} or ${any path} 2+2
current value being evaluated. If an array is used in switch, Expression mode starts with a number.
each element of the array is tested. Examples:
Example: $a = 1 "text"
$var = "word1","word2","word3" ${!@#$%^&*()}=3 Expression mode starts with a quotation mark.
switch -regex ($var) { $global:a = 1 # Visible everywhere
"word1" {"Multi-match Exact " + $_ } $local:a = 1 # defined in this scope and visible to children text
"word2" {"Multi-match Exact " + $_ } $private:a=1 # same as local but invisible to child scopes Command mode starts with a letter.
"w.*2" {"Pattern match Exact " + $_ } $script:a=1 # visible to everything in this script
default {"Multi-match Default " + $_ } $env:path = “d:\windows” & "text"
} ${C:\TEMP\testfile.txt}=”This writes to a file” Command mode starts with an ampersand.
Get-Variable –scope 1 a #Gets value from the parent scope
Output: Get-Variable –scope 2 a # grandparent . "file.ps1"
Multi-match Exact word1 Command mode starts with a dot followed by a space.
Multi-match Exact word2
Pattern match Exact word2 While (Scripting) .125
Multi-match Default word3 [:label] while (condition) Expression mode starts with a dot, which is followed by a
{ number—not a space or a letter.
Throw …
Throw provides the same functionality for scripts as the } .text
ThrowTerminatingError API does for cmdlets. Command mode starts with a dot, which is part of the
throw "Danger, Danger" do command name ".text"
Danger, Danger {
At line:1 char:6 … It is very useful to be able to mix expressions and commands;
+ throw <<<< "Danger, Danger" } while (condition) which you can do by using parentheses. Inside parentheses, the
Throw takes a string, exception, or ErrorRecord as an mode discovery process starts over.
argument. Write-Host (2+2)
2+2 is treated as an expression to evaluate and is passed to
Traps Parsing the Write-Host command.
Trap [ExceptionType] { Windows PowerShell parses in two modes—command mode (Get-Date).day + 2
if (…) and expression mode. In expression mode, Windows Get-Date is treated as a command, and the result of
{ continue PowerShell parses as most high-level languages parse: numbers executing it becomes the left value in the expression.
# continue at the script statement after the one that cased the are numbers; strings need to be quoted, and so on. Expressions You can nest commands and expressions without restrictions.
# trap; $? is updated but no error record is generated are things such as: Write-Host ((Get-Date).day + 2)
} else (…) 2+2 Get-Date is a command. ((Get-Date).day+2) is an
{ Break 4 expression, and Write-Host ((Get-Date).day + 2) is a
# rethrow the exception "Hello" + " world" command again.
} Hello world Write-Host ((Get-Date) - (Get-Date).date)
# Doing nothing will do what is specified in the $a = "hi" The Get-Date command is used twice to determine how
# $ErrorActionPreference setting $a.length * 13 much time has passed since midnight (condition).
} 26
When parsing in command mode, strings do not need to be
quoted and everything is treated like a string except variables
Type Operations (Scripting) and things in parentheses. For example:
copy users.txt accounts.txt
-is IS type (e.g. $a -is [int] ) users.txt and accounts.txt are treated as strings
-as convert to type (e.g. 1 -as [string] treats 1 as a string ) write-host 2+2
2+2 is treated as string, not an expression to evaluate
Until (Scripting) copy $src $dest
$src and $dest are variables. Not needing to use quotation
do marks when working in a command shell can be very beneficial