Skip to content

/cheatsheets/powershell/powershell-cheat-sheet

PowerShell cheat sheet: files, objects, filtering, strings and error handling

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
PowerShell
versions
Windows PowerShell 5.1, PowerShell 7.x
os
windows, linux, macos

PowerShell commands are cmdlets named Verb-Noun, and they pass objects, not text, through the pipeline. Learn three commands first: Get-Command (find a command), Get-Help (read its help) and Get-Member (see what properties an object has).

Discover

TaskCommand
Find commandsGet-Command *service* / Get-Command -Module ActiveDirectory
Help with examplesGet-Help Get-ChildItem -Examples (Update-Help once, as admin)
Properties and methods of outputGet-Process | Get-Member
Syntax of a cmdletGet-Command Copy-Item -Syntax
What an alias points toGet-Alias ls / Get-Alias -Definition Get-ChildItem
Version and edition$PSVersionTable

Files

TaskCommandbash
List / recursive / files onlyGet-ChildItem / -Recurse / -Filels, find . -type f
Read / first or last linesGet-Content f.txt / -TotalCount 10 / -Tail 10cat, head, tail
Follow a logGet-Content app.log -Wait -Tail 20tail -f
Write / appendSet-Content f.txt "x" / Add-Content f.txt "y"> and >>
Copy / move / deleteCopy-Item, Move-Item, Remove-Item -Recursecp, mv, rm -r
Test a pathTest-Path .\out[ -e out ]
Search textSelect-String -Path *.log -Pattern 'error'grep
Size of a folder(Get-ChildItem -Recurse -File | Measure-Object Length -Sum).Sumdu -sb

Objects: filter, sort, select

powershell
$items = @(
  [pscustomobject]@{ Name = 'api';    Cpu = 120; Status = 'Running' }
  [pscustomobject]@{ Name = 'worker'; Cpu = 15;  Status = 'Stopped' }
  [pscustomobject]@{ Name = 'web';    Cpu = 80;  Status = 'Running' }
)
$items | Where-Object Status -eq 'Running' | Sort-Object Cpu -Descending | Select-Object Name, Cpu | Format-Table -AutoSize | Out-String -Width 60
'Total CPU: ' + ($items | Measure-Object Cpu -Sum).Sum
$items | Group-Object Status | ForEach-Object { '{0}: {1}' -f $_.Name, $_.Count }
'Names: ' + ($items.Name -join ', ')
$items | Select-Object Name, @{ Name = 'CpuPct'; Expression = { '{0:N1}%' -f ($_.Cpu / 2) } } | ConvertTo-Csv -NoTypeInformation

Output

Name Cpu
---- ---
api  120
web   80

Total CPU: 215
Running: 2
Stopped: 1
Names: api, worker, web
"Name","CpuPct"
"api","60.0%"
"worker","7.5%"
"web","40.0%"

Strings and operators

powershell
$name = 'errcodex'
"Hello $name, length $($name.Length)"
'single quotes do not expand $name'
'{0}-{1:D3}' -f 'build', 7
'a,b,c' -split ','
'one two' -replace 'two', '2'
'Report.TXT' -like '*.txt'
'id=42' -match 'id=(\d+)' | Out-Null; $Matches[1]
'  trim me  '.Trim().ToUpper()
1..5 -contains 3

Output

Hello errcodex, length 8
single quotes do not expand $name
build-007
a
b
c
one 2
True
42
TRIM ME
True
OperatorMeaning
-eq -ne -gt -ge -lt -lecomparison (case-insensitive for strings; -ceq for case-sensitive)
-like / -notlikewildcards * and ?
-match / -notmatchregular expression; captures in $Matches
-in / -containsmembership in a collection
-and -or -not !logic
-split -join -replacestring operations (regex for -split and -replace)

Variables, hashtables, loops

powershell
$config = @{ Env = 'prod'; Port = 8080 }
$config.Region = 'westeurope'
$config.Keys | Sort-Object | ForEach-Object { "$_ = $($config[$_])" }
foreach ($n in 1..3) { "loop $n" }
$squares = 1..4 | ForEach-Object { $_ * $_ }
"squares: $($squares -join ' ')"
switch ('beta') { 'alpha' { 'first' } 'beta' { 'second' } default { 'other' } }

Output

Env = prod
Port = 8080
Region = westeurope
loop 1
loop 2
loop 3
squares: 1 4 9 16
second

Errors and exit codes

TaskCode
Make cmdlet errors catchable$ErrorActionPreference = 'Stop' or -ErrorAction Stop
Catchtry { ... } catch { $_.Exception.Message } finally { ... }
Exit code of last native program$LASTEXITCODE
Did the last command succeed$?
Leave a script with a codeexit 3

System

powershell
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
Get-Service | Where-Object Status -eq 'Running'
Get-NetTCPConnection -State Listen | Sort-Object LocalPort
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, LastBootUpTime
Test-NetConnection example.org -Port 443
Get-WinEvent -LogName System -MaxEvents 20

Sources

cheat sheets · cmdcmd cheat sheet: files, variables, batch syntax and network commandsCommand Prompt cheat sheet: files and folders, variables and substrings, if and for in batch files, plus ipconfig, netstat -ano, tasklist and systeminfo.glossary · powershellWhat is splatting in PowerShell? (@params instead of $params)Splatting passes a hashtable of parameter names and values to a command as @name instead of $name. It replaces long lines and lets you add options in code.flags · powershellPowerShell -ErrorAction Stop: why try/catch does not catch the errortry/catch only catches terminating errors, and most cmdlet errors are not. Add -ErrorAction Stop, or set $ErrorActionPreference to Stop, to catch them.commands · powershellSelect-String: the PowerShell equivalent of grepSelect-String -Path *.log -Pattern error prints matching lines with file and line number. It ignores case by default; see -CaseSensitive, -NotMatch, -Context.commands · powershellGet-FileHash: get the SHA256 or MD5 hash of a file in PowerShellGet-FileHash FILE prints a file's SHA256 hash in PowerShell; -Algorithm MD5, SHA1 or SHA512 picks another. Compare it with -eq, which ignores hex letter case.commands · powershellCompress-Archive: zip a folder in PowerShell (and unzip it with Expand-Archive)Compress-Archive -Path folder -DestinationPath out.zip zips a folder in PowerShell; Expand-Archive unzips. Zip only, files under 2 GB, hidden files skipped.flags · powershellGet-ChildItem -Recurse -Filter vs -Include: find files in subfoldersGet-ChildItem -Recurse -Filter *.log finds files in all subfolders. Tested: -Filter vs -Include and -Exclude, -Depth, and why -Include alone returns nothing.