Skip to content
neztach edited this page Aug 31, 2023 · 1 revision
Code> Explanation
If (1 -eq 1) { }
Do something if 1 is equal to 1
Do { 'hi' } While ($false)
Loop while a condition is true (always executes at least once)
While ($false) { 'hi' }
While loops are not guaranteed to run at least once
While ($true) { }
Do something indefinitely
While ($true) { if (1 -eq 1) { break } }
Break out of an infinite while loop conditionally
For ($i = 0; $i -le 10; $i++) { Write-Host $i }
Iterate using a for..loop
ForEach ($item in (Get-Process)) { }
Iterate over items in an array
Switch ('test') { 'test' { 'matched'; break } }
Use the switch statement to perform actions based on conditions. Returns string 'matched'
Switch -Regex (@('Trevor', 'Daniel', 'Bobby')) {
    'o' { $PSItem; 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')) {
    'e' { $PSItem }
    'r' { $PSItem }
}
Switch statement omitting the break statement. Inputs can be matched multiple times, in this scenario.

Clone this wiki locally