PowerShell Cheat Sheet
Navigation and files
// move around and manage files
Get-Location; Set-Location C:\code; Get-ChildItem -Force
New-Item -ItemType Directory app; New-Item file.txt
Copy-Item a.txt b.txt; Move-Item b.txt old\; Remove-Item old -Recurse
Get-Content f.txt -Tail 20 -Wait; Set-Content f.txt "hi"; Add-Content f.txt "more"
Test-Path f.txt; Resolve-Path .\f.txt
Variables and strings
$x = 5; [int]$n = "42"; $arr = 1, 2, 3; $h = @{ a = 1 }
"Total: $($a + $b)"; "{0:N2}" -f 3.14159; $s.ToUpper(); $s.Split(",")
"a,b" -split ","; $arr -join ";"; $s -replace "old", "new"
Control flow
if ($a -gt 5) { } elseif ($a -eq 5) { } else { }
switch ($x) { 1 { "one" } default { "other" } }
foreach ($i in 1..5) { }; for ($i = 0; $i -lt 5; $i++) { }
while ($c) { }; do { } until ($c)
Pipeline
Get-Process | Where-Object CPU -gt 100 | Sort-Object CPU -Descending | Select-Object -First 5
Get-Service | Group-Object Status
1..10 | ForEach-Object { $_ * 2 } | Measure-Object -Sum
Get-ChildItem | Export-Csv files.csv -NoTypeInformation
Import-Csv data.csv | ConvertTo-Json
Functions and errors
function Do-Thing { param([Parameter(Mandatory)][string]$Name, [int]$Count = 1) "$Name x$Count" }
try { Risky -ErrorAction Stop } catch { $_.Exception.Message } finally { }
Invoke-RestMethod https://api.example.com/items
Get-ChildItem *.tmp | Remove-Item -WhatIf
Full PowerShell documentation