๐Ÿ’ป

PowerShell Cheat Sheet

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.

Jump to: Your first scriptVariablesif / else LoopsThe pipelineArrays & hashtables ๐Ÿš€ Practice problems

Your first script

Write-Host "Hello, world!"
๐Ÿ“ PowerShell cmdlets follow a Verb-Noun naming pattern โ€” Get-Process, Write-Host, Set-Location โ€” which makes them predictable once you learn the pattern.

Variables

$age = 25
$name = "Sam"
$price = 19.99

if / else

$age = 20
if ($age -ge 18) {
    Write-Host "Adult"
} elseif ($age -ge 13) {
    Write-Host "Teen"
} else {
    Write-Host "Child"
}
๐Ÿ“ PowerShell uses -eq, -ge, -lt etc. instead of ==, >=, < for comparisons.

Loops

for ($i=0; $i -lt 5; $i++) {
    Write-Host $i
}

$n = 3
while ($n -gt 0) {
    Write-Host $n
    $n--
}

The pipeline

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 }

Arrays & hashtables

$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

๐Ÿš€ Practice problems

Full runnable scripts, run in a real PowerShell (pwsh) sandbox โ€” same workspace as the other cheat sheets.

Sum an array EASY

$nums = 4, 8, 15, 16, 23, 42
$sum = 0
foreach ($n in $nums) { $sum += $n }
Write-Host $sum

Reverse a string MEDIUM

function Reverse-Str($s) {
    $arr = $s.ToCharArray()
    [array]::Reverse($arr)
    return -join $arr
}

Write-Host (Reverse-Str "powershell")

FizzBuzz MEDIUM

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 }
}

Word frequency with a hashtable HARD

$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])"
}