PowerShell: Flow Control Cheat Sheet

# Do something if 1 is equal to 1
if (1 -eq 1) { }
# Loop while a condition is true (always executes at least once)
do { 'hi' } while ($false)
# While loops are not guaranteed to run at least once
while ($false) { 'hi' }
# Do something indefinitely
while ($true) { }
# Break out of an infinite while loop conditionally
while ($true) { if (1 -eq 1) { break } }
# Iterate using a for..loop
for ($i = 0; $i -le 10; $i++) { Write-Host $i }
# Iterate over items in an array
foreach ($item in (Get-Process)) { }
# Use the switch statement to perform actions based on conditions. Returns string 'matched'
switch ('test') { 'test' { 'matched'; break } } 

# Use the switch statement with regular expressions to match inputs
# NOTE: $PSItem or $_ refers to the "current" item being matched in the array
switch -regex (@('Trevor', 'Daniel', 'Bobby')) { 
  'o' { $PSItem; break } 
}
# Switch statement omitting the break statement. Inputs can be matched multiple times, in this scenario.
switch -regex (@('Trevor', 'Daniel', 'Bobby')) {
  'e' { $PSItem }
  'r' { $PSItem }
}
If If($x ­eq 5){} Elseif$x ­gt 5  Else 
While$x = 1; while($x ­lt 10){$x;$x++}
ForFor($i=0; $i ­lt 10; $i++){ $i }
ForeachForeach($file in dir C:){$file.Nam
Foreach1..10 | foreach{$_}
SwitchSwitch ­options (){
PatternX {statement}
Default {Default Statement} 

PowerShell: Variables Cheat Sheet

$a = 0Initialize a variable
[int] $a = 'Trevor'Initialize a variable, with the specified type (throws an exception)
[string] $a = 'Trevor'Initialize a variable, with the specified type (doesn’t throw an exception)
Get-Command -Name *varia*Get a list of commands related to variable management
Get-VariableGet an array of objects, representing the variables in the current and parent scopes
Get-Variable | ? { $PSItem.Options -contains 'constant' }Get variables with the “Constant” option set
Get-Variable | ? { $PSItem.Options -contains 'readonly' }Get variables with the “ReadOnly” option set
New-Variable -Name FirstName -Value Trevor
New-Variable FirstName -Value Trevor -Option ConstantCreate a constant variable, that can only be removed by restarting PowerShell
New-Variable FirstName -Value Trevor -Option ReadOnlyCreate a variable that can only be removed by specifying the -Force parameter on Remove-Variable
Remove-Variable -Name firstnameRemove a variable, with the specified name
Remove-Variable -Name firstname -ForceRemove a variable, with the specified name, that has the “ReadOnly” option set

PowerShell: Functions Cheat Sheet

# A basic PowerShell function

function add ($a, $b) { $a + $b }
# A PowerShell Advanced Function, with all three blocks declared: BEGIN, PROCESS, END

function Do-Something {
  [CmdletBinding]()]
  param ()
  begin { }
  process { }
  end { }
}

		

PowerShell: Loop Cheat Sheet

# Do While Loop
$a=1
Do {$a; $a++}
While ($a –lt 10)
# Do Until Loop
$a=1
Do {$a; $a++}
Until ($a –gt 10)
# For Loop
For ($a=1; $a –le 10; $a++)
{$a}
# ForEach – Loop Through Collection of Objects
Foreach ($i in Get-Childitem c:\windows)
{$i.name; $i.creationtime}

PowerShell: Essential Cheat Sheet

Get-Command# Retrieves a list of all the commands available to PowerShell
# (native binaries in $env:PATH + cmdlets / functions from PowerShell modules)
Get-Command -Module Microsoft*Retrieves a list of all the PowerShell commands exported from modules named Microsoft*
Get-Command -Name *itemRetrieves a list of all commands (native binaries + PowerShell commands) ending in “item”
Get-HelpGet all help topics
Get-Help -Name about_VariablesGet help for a specific about_* topic (aka. man page)
Get-Help -Name Get-CommandGet help for a specific PowerShell function
Get-Help -Name Get-Command -Parameter ModuleGet help for a specific parameter on a specific command

PowerShell: Operators Cheat Sheet

$a = 2The basic variable assignment operator
$a += 1Incremental assignment operator
$a -= 1Decrement assignment operator
$a -eq 0Equality comparison operator
$a -ne 5Not-equal comparison operator
$a -gt 2Greater than comparison operator
$a -lt 3Less than comparison operator
$FirstName = 'Trevor'

$FirstName -like 'T*'
Perform string comparison using the -like operator, which supports the wildcard (*) character. Returns $true

PowerShell: Regular Expressions Cheat Sheet

Below is a regular expression list

.matches any character except newline
\escape character
\wword character [a-zA-Z_0-9]
\Wnon-word character [^a-zA-Z_0-9]
\dDigit [0-9]
\Dnon-digit [^0-9]
\nnew line
\rcarriage return
\ttabulation
\swhite space
\Snon-white space
^beginning of a line
$end of a line
\Abeginning of the string (multi-line match)
\Zend of the string (multi-line match)
\bword boundary, boundary between \w and \W
\Bnot a word boundary
\<beginning of a word
\>end of a word
{n}matches exaclty n times
{n,}matches a minimum of n times
{x,y}matches a min of x and max of y
(a|b)‘a’ or ‘b’
*matches 0 or more times
+matches 1 or more times
?matches 1 or 0 times
*?matches 0 or more times, but as few as possible
+?matches 1 or more times, but as few as possible
??matches 0 or 1 time
#Match while tagging match groups 
'CowColour Brown' -match '(?<Attribute>\w+) (?<Value>\w+)' | out-null $matches.Attribute $matches.Value 
#cowColour 
#Brown
#Matching groups - your $matches object will have properties containing the valid matches 
"Subnet:10.1.1.0/24" -match 'Subnet:(?<SiteSubnet>(?:\d{1,3}\.){3}\d{1,3}/\d+)'
#Replace to reformat a string 
'This is a wild test' -replace '.*(w[^ ]+).*','Not so $1' 
#Not so wild
#Lazy matching (to prevent over-matching) use a ? after the + or * 
"<h1>MyHeading</h1>" -replace '<([^/]+?)>','<cow>' -replace '</([^/]+?)>','</cow>' 
#<cow>MyHeading</cow>
#negative lookbehind 
($DistinguishedName -split '(?<!\\),')[1..100] -join ','

PowerShell: Commands List Cheat Sheet

cd, chdir, slSets the current working location to a specified location.
cat, gc, typeGets the content of the item at the specified location.
acAdds content to the specified items, such as adding words to a file.
scWrites or replaces the content in an item with new content.
copy, cp, cpiCopies an item from one location to another.
del, erase, rd, ri, rm, rmdirDeletes the specified items.
mi, move, mvMoves an item from one location to another.
siChanges the value of an item to the value specified in the command.
niCreates a new item.
sajbStarts a Windows PowerShell background job.
compare, difCompares two sets of objects.
groupGroups objects that contain the same value for specified properties.
curl, iwr, wgetGets content from a web page on the Internet.
measureCalculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files …
rvpaResolves the wildcard characters in a path, and displays the path contents.
rujbRestarts a suspended job
set, svSets the value of a variable. Creates the variable if one with the requested name does not exist.
shcmCreates Windows PowerShell commands in a graphical command window.
sortSorts objects by property values.
sasvStarts one or more stopped services.
saps, startStarts one or more processes on the local computer.
sujbTemporarily stops workflow jobs.
wjbSuppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are …
?, whereSelects objects from a collection based on their property values.
echo, writeSends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline,…