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} 

Leave a Reply

Your email address will not be published. Required fields are marked *