Microsoft's scripting shell for Windows automation and system administration โ cmdlets pass real objects down the pipeline instead of raw text, which is what separates it from bash. The backbone of most Windows IT-admin tooling. Copy-paste examples plus live Run/Submit exercises.
Write-Host "Hello, world!"
Verb-Noun naming pattern โ Get-Process, Write-Host, Set-Location โ which makes them predictable once you learn the pattern.$age = 25
$name = "Sam"
$price = 19.99
$age = 20
if ($age -ge 18) {
Write-Host "Adult"
} elseif ($age -ge 13) {
Write-Host "Teen"
} else {
Write-Host "Child"
}
-eq, -ge, -lt etc. instead of ==, >=, < for comparisons.for ($i=0; $i -lt 5; $i++) {
Write-Host $i
}
$n = 3
while ($n -gt 0) {
Write-Host $n
$n--
}
PowerShell's superpower โ cmdlets pass full .NET objects to each other via |, not plain text.
Get-Process | Where-Object { $_.CPU -gt 10 } | Sort-Object CPU -Descending
1..10 | ForEach-Object { $_ * 2 }
$nums = 10, 20, 30
$nums += 40
Write-Host $nums[0] # 10
Write-Host $nums.Count # 4
$ages = @{ "Sam" = 25; "Ana" = 30 }
Write-Host $ages["Sam"] # 25
Full runnable scripts, run in a real PowerShell (pwsh) sandbox โ same workspace as the other cheat sheets.
$nums = 4, 8, 15, 16, 23, 42
$sum = 0
foreach ($n in $nums) { $sum += $n }
Write-Host $sum
function Reverse-Str($s) {
$arr = $s.ToCharArray()
[array]::Reverse($arr)
return -join $arr
}
Write-Host (Reverse-Str "powershell")
for ($i=1; $i -le 15; $i++) {
if ($i % 15 -eq 0) { Write-Host "FizzBuzz" }
elseif ($i % 3 -eq 0) { Write-Host "Fizz" }
elseif ($i % 5 -eq 0) { Write-Host "Buzz" }
else { Write-Host $i }
}
$text = "the cat sat on the mat the cat ran"
$counts = @{}
foreach ($word in $text.Split(" ")) {
if (-not $counts.ContainsKey($word)) { $counts[$word] = 0 }
$counts[$word]++
}
foreach ($word in $counts.Keys) {
Write-Host "$word`: $($counts[$word])"
}