/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
| Task | Command |
|---|---|
| Find commands | Get-Command *service* / Get-Command -Module ActiveDirectory |
| Help with examples | Get-Help Get-ChildItem -Examples (Update-Help once, as admin) |
| Properties and methods of output | Get-Process | Get-Member |
| Syntax of a cmdlet | Get-Command Copy-Item -Syntax |
| What an alias points to | Get-Alias ls / Get-Alias -Definition Get-ChildItem |
| Version and edition | $PSVersionTable |
Files
| Task | Command | bash |
|---|---|---|
| List / recursive / files only | Get-ChildItem / -Recurse / -File | ls, find . -type f |
| Read / first or last lines | Get-Content f.txt / -TotalCount 10 / -Tail 10 | cat, head, tail |
| Follow a log | Get-Content app.log -Wait -Tail 20 | tail -f |
| Write / append | Set-Content f.txt "x" / Add-Content f.txt "y" | > and >> |
| Copy / move / delete | Copy-Item, Move-Item, Remove-Item -Recurse | cp, mv, rm -r |
| Test a path | Test-Path .\out | [ -e out ] |
| Search text | Select-String -Path *.log -Pattern 'error' | grep |
| Size of a folder | (Get-ChildItem -Recurse -File | Measure-Object Length -Sum).Sum | du -sb |
Objects: filter, sort, select
$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 -NoTypeInformationOutput
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
$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 3Output
Hello errcodex, length 8 single quotes do not expand $name build-007 a b c one 2 True 42 TRIM ME True
| Operator | Meaning |
|---|---|
| -eq -ne -gt -ge -lt -le | comparison (case-insensitive for strings; -ceq for case-sensitive) |
| -like / -notlike | wildcards * and ? |
| -match / -notmatch | regular expression; captures in $Matches |
| -in / -contains | membership in a collection |
| -and -or -not ! | logic |
| -split -join -replace | string operations (regex for -split and -replace) |
Variables, hashtables, loops
$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
| Task | Code |
|---|---|
| Make cmdlet errors catchable | $ErrorActionPreference = 'Stop' or -ErrorAction Stop |
| Catch | try { ... } catch { $_.Exception.Message } finally { ... } |
| Exit code of last native program | $LASTEXITCODE |
| Did the last command succeed | $? |
| Leave a script with a code | exit 3 |
System
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 20Sources
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/scripting/overview
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators
- learn.microsoft.comlearn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators
Related pages
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.