This cheat sheet includes basic syntax and methods to help you using PowerShell. PowerShell is a cross-platform task automation and configuration management framework, consisting of a command-line shell and scripting language.
# 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 }
}
# 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 { }
}
#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>