PowerShell Cheat Sheet
PowerShell pipes objects between commands, not text. Commands follow a Verb-Noun pattern. Works on Windows PowerShell 5.1 and PowerShell 7+ (pwsh).
On this page
Getting Help #
| Command | Action |
|---|---|
| Show examples for a command | |
| Find commands by name | |
| Show the properties and methods of the output | |
| See what an alias points to | |
| Download help files (admin only in Windows PowerShell 5.1) |
Common Aliases #
| Alias | Real command |
|---|---|
| , | ( only on Windows) |
| (Windows only) | |
| / / | / / (Windows only) |
| / | / (Windows only) |
Files & Folders #
| Command | Action |
|---|---|
| List, including hidden files | |
| Find files recursively | |
| Create a file | |
| Create a folder ( also works) | |
| Delete a folder and its contents (permanent, no Recycle Bin, no prompt) | |
| Copy a folder | |
| Rename | |
| Follow a log file (like ) | |
| Write (overwrite) | |
| Append | |
| Check whether a path exists | |
| Search text in files (like grep) | |
| Create a zip | |
| Extract a zip | |
| File checksum | |
| Open the current folder in Explorer () |
Pipeline #
| Command | Action |
|---|---|
Filter ($_ = current item) | |
| Pick properties / first N | |
| Sort | |
| Group and count | |
| Count, sum, average | |
| Run code for each item | |
| Table output | |
| Show all properties | |
| Interactive, filterable window (Windows) | |
| Save as CSV | |
| Read a CSV as objects | |
| / | JSON conversion |
Comparison Operators #
| Operator | Meaning |
|---|---|
-eq -ne | Equal / not equal |
-gt -ge -lt -le | Greater / less than (or equal) |
-like "*.txt" | Wildcard match |
-match "^\d+$" | Regex match |
-contains / -in | Collection contains a value |
-and -or -not | Logic |
Processes & Services #
| Command | Action |
|---|---|
| Top CPU processes | |
| Kill a process by name | |
| Start as administrator | |
| Running services | |
| Restart a service |
Network #
| Command | Action |
|---|---|
| Ping | |
| Test whether a port is open | |
| DNS lookup | |
| IP configuration | |
| Download a file | |
| Call an API (parses JSON automatically) |
Variables & Environment #
| Syntax | Meaning |
|---|---|
$name = "Milan" | Set a variable |
"Hello $name" | Variables expand in double quotes (not in single quotes) |
$env:PATH | Read an environment variable |
$env:API_KEY = "x" | Set it for this session |
$PROFILE | Path to your profile script (runs at startup) |
$? / $LASTEXITCODE | Did the last command succeed? / exit code of the last program |
$null, $true, $false | Built-in values |
Script Basics #
function Get-Greeting([string]$Name = "World") {
"Hello, $Name!"
}
foreach ($file in Get-ChildItem *.txt) {
if ($file.Length -gt 1KB) { Write-Host "$($file.Name) is big" }
}
try { Get-Item missing.txt -ErrorAction Stop }
catch { Write-Warning $_.Exception.Message }
Keyboard (PSReadLine) #
| Key | Action |
|---|---|
Tab / Shift + Tab | Cycle completions |
Ctrl + Space | Show all completions as a menu |
Ctrl + R | Search history |
F2 | Toggle inline / list prediction view (PSReadLine 2.2+, built into PS 7.3+) |
→ | Accept inline suggestion |
Ctrl + C | Stop the command |
Tips #
- Scripts blocked? Run
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned. - Line continuation: end the line with a backtick
`or with a pipe|. - Install PowerShell 7:
winget install Microsoft.PowerShell.
Get-Helpalso: help manDocumentation for any command. Get-Help name [options]
| Parameter | What it does |
|---|---|
-Examples | Only the examples |
-Detailed | Description of every parameter |
-Full | Everything |
-Online | Open the web page |
-Parameter Path | Help for one parameter |
-ShowWindow | Help in a searchable window (Windows only, also PowerShell 7) |
Get-Help *process* | Search help topics |
Get-Help about_* | Conceptual topics (about_Operators, about_If…) |
Get-Commandalso: gcmFind commands. Get-Command [name] [options]
| Parameter | What it does |
|---|---|
*service* | Wildcard search by name |
-Verb Get | All commands with a verb |
-Noun Process | All commands about a noun |
-Module NetTCPIP | Commands from one module |
-CommandType Cmdlet | Only cmdlets (Alias, Function, Application) |
-Syntax | Show the syntax |
gcm git | Where an external program is (like which) |
Get-Processalso: ps gpsRunning processes. Get-Process [name] [options]
| Parameter | What it does |
|---|---|
chrome | By name (wildcards OK) |
-Id 1234 | By process ID |
-IncludeUserName | Show the owner (admin) |
-FileVersionInfo | Version of the program file |
-Module | Loaded DLLs |
ps | sort CPU -Desc | select -First 10 | Top CPU users |
Get-Aliasalso: galShow aliases. Get-Alias [name] [options]
| Usage / parameter | What it does |
|---|---|
Get-Alias | All aliases |
Get-Alias ls | What ls points to |
-Definition Get-ChildItem | All aliases of a command |
Set-Alias np notepad | Create an alias (put it in $PROFILE to keep it) |
Update-HelpDownload the newest help files (admin needed only in Windows PowerShell 5.1). Update-Help [options]
| Parameter | What it does |
|---|---|
-UICulture en-US | Language of the help |
-Module Microsoft.PowerShell.* | Only some modules |
-Force | Update even if done today |
-ErrorAction SilentlyContinue | Ignore modules without online help |
Get-ChildItemalso: ls dir gciList files and folders (also registry keys, certificates…). Get-ChildItem [path] [options]
| Parameter | What it does |
|---|---|
-Force | Include hidden and system items |
-Recurse | Include all subfolders |
-Depth 2 | Recurse at most 2 levels |
-Filter *.log | Fast filter by name |
-Include *.jpg, *.png | Several patterns (use with -Recurse or a \* path) |
-Exclude *.tmp | Skip patterns |
-File / -Directory | Files only / folders only |
-Hidden | Only hidden items |
-Name | Names only (strings) |
-Attributes ReadOnly | Filter by attribute |
-FollowSymlink | Follow links while recursing |
Example: Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, Length
Set-Locationalso: cd sl chdirChange the current folder (or drive, e.g. HKCU:). Set-Location [path]
| Usage / parameter | What it does |
|---|---|
cd C:\dev | Go to a folder (drive changes automatically) |
cd .. / cd ~ | Up one / home folder |
cd - / cd + | Back / forward in the location history (PowerShell 6.2+) |
-LiteralPath | Path with [ ] characters, no wildcards |
-PassThru | Output the new location |
Push-Location / Pop-Location | Remember a folder and come back (pushd / popd) |
Get-Locationalso: pwd glCurrent folder. Get-Location
| Usage | What it does |
|---|---|
pwd | Show the current location |
(Get-Location).Path | As a plain string |
$PWD | Automatic variable with the same value |
-Stack | Locations saved with Push-Location |
Get-Contentalso: cat gc typeRead a file. Get-Content path [options]
| Parameter | What it does |
|---|---|
-Tail 20 | Last 20 lines |
-TotalCount 20 (-Head) | First 20 lines |
-Wait | Keep reading new lines (like tail -f) |
-Raw | Whole file as one string (not an array of lines) |
-Encoding utf8 | Choose the encoding |
-Delimiter "," | Split on a delimiter instead of new lines |
-AsByteStream | Raw bytes (PowerShell 7; Windows PowerShell: -Encoding Byte) |
Copy-Itemalso: cp copy cpiCopy files and folders. Copy-Item source destination [options]
| Parameter | What it does |
|---|---|
-Recurse | Copy a folder with its contents |
-Force | Also copy over read-only files and aliases |
-Filter *.txt | Only matching files |
-Exclude *.tmp | Skip matching files |
-Container:$false | Flatten: don't recreate the folder structure |
-PassThru | Output the copied items |
-WhatIf | Show what would happen |
-ToSession $s | Copy to a remote PowerShell session |
Move-Itemalso: mv move miMove or rename files and folders. Move-Item source destination [options]
| Parameter | What it does |
|---|---|
-Force | Overwrite existing files |
-Filter / -Include / -Exclude | Choose which files |
-PassThru | Output the moved items |
-WhatIf | Preview |
Remove-Itemalso: rm del rmdir ri eraseDelete files and folders (no Recycle Bin). Remove-Item path [options]
| Parameter | What it does |
|---|---|
-Recurse | Delete a folder with everything in it |
-Force | Also hidden / read-only items, no prompts |
-Include / -Exclude / -Filter | Choose which files |
-WhatIf | ✓ Show what would be deleted |
-Confirm | Ask for every item |
-LiteralPath | Paths with [ ] |
Write-Outputalso: echo writeSend objects or text to the pipeline. Write-Output value
| Usage | What it does |
|---|---|
echo "Hello" | Print text |
-NoEnumerate | Output a collection as one object |
Write-Host "Hi" -ForegroundColor Green | Coloured text straight to the screen (not the pipeline) |
Write-Warning / Write-Error / Write-Verbose | Other output streams |
Clear-Hostalso: cls clearClear the screen. Shortcut: Ctrl + L (PSReadLine).
| Usage | What it does |
|---|---|
cls | Clear the console |
Stop-Processalso: kill sppsEnd processes. Stop-Process [options]
| Parameter | What it does |
|---|---|
-Name notepad | By name |
-Id 1234 | By process ID |
-Force | No confirmation, even for processes you don't own |
-PassThru | Output the stopped processes |
-WhatIf | Preview |
New-Itemalso: niCreate files, folders, links. New-Item path [options]
| Parameter | What it does |
|---|---|
New-Item notes.txt | Empty file |
-ItemType Directory | Folder (mkdir name does the same) |
-ItemType SymbolicLink -Target C:\real | Symbolic link (HardLink, Junction) |
-Value "text" | File with content |
-Force | Overwrite / create parent folders |
-Name x -Path C:\dev | Name and location separately |
mkdirCreate folders. mkdir [options] folder…
| Option | What it does |
|---|---|
-p, --parents | Create parent folders as needed; no error if it exists |
-v, --verbose | Print every folder created |
-m 755 | Set permissions while creating |
mkdir -p src/{components,pages,utils} | Several subfolders in one go |
Rename-Itemalso: ren rniRename a file or folder. Rename-Item path newName
| Usage / parameter | What it does |
|---|---|
Rename-Item old.txt new.txt | Rename |
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.md' } | Bulk rename |
-Force | Hidden / read-only items |
-PassThru | Output the renamed item |
-WhatIf | Preview |
tailShow the last lines of a file, or follow it live. tail [options] file…
| Option | What it does |
|---|---|
-n 50 | Last 50 lines (default 10) |
-n +100 | Everything from line 100 on |
-f | Follow: keep printing new lines (logs) |
-F | Follow and survive log rotation / file recreated |
-c 200 | Last 200 bytes |
--pid=1234 | Stop following when that process ends |
-s 5 | Check for new lines every 5 seconds (with -f) |
-q | No file-name headers |
Example: tail -f /var/log/syslog | grep error
Set-Contentalso: scWrite text to a file (replaces the content). Set-Content path value [options]
| Parameter | What it does |
|---|---|
-Value "text" | What to write (or pipe it in) |
-Encoding utf8 | Encoding (utf8NoBOM in PowerShell 7) |
-NoNewline | No newline at the end |
-Force | Overwrite read-only files |
-PassThru | Output what was written |
Add-Contentalso: acAppend text to a file. Add-Content path value [options]
| Parameter | What it does |
|---|---|
-Value "line" | What to append |
-Encoding utf8 | Encoding |
-NoNewline | Don't add a newline |
-Force | Also hidden / read-only files |
Test-PathDoes a path exist? Returns True / False. Test-Path path [options]
| Parameter | What it does |
|---|---|
-PathType Leaf | Must be a file (Container = folder) |
-IsValid | Is the syntax valid (doesn't need to exist) |
-NewerThan (Get-Date).AddDays(-1) | Changed in the last day |
-OlderThan | Older than a date |
Select-Stringalso: slsSearch text in files or output (PowerShell's grep). Select-String pattern [path] [options]
| Parameter | What it does |
|---|---|
-Path *.log | Files to search |
-Pattern "error" | Regex to find |
-SimpleMatch | Plain text, no regex |
-CaseSensitive | Match case (default is case-insensitive) |
-NotMatch | Lines that don't match |
-Context 2,3 | 2 lines before, 3 after |
-AllMatches | Every match on a line |
-List | Only the first match per file |
-Raw | Output the lines only (PowerShell 7) |
-Recurse | (use Get-ChildItem -Recurse | Select-String) |
Compress-ArchiveCreate a zip file. Compress-Archive -Path src -DestinationPath out.zip [options]
| Parameter | What it does |
|---|---|
-Path folder\* | What to zip (folder = includes the folder itself) |
-DestinationPath out.zip | The zip file |
-Update | Add/replace files in an existing zip |
-Force | Overwrite an existing zip |
-CompressionLevel Fastest | Optimal, Fastest, NoCompression |
Expand-ArchiveExtract a zip file. Expand-Archive path [-DestinationPath folder]
| Parameter | What it does |
|---|---|
-DestinationPath folder | Where to extract (default: a folder named like the zip) |
-Force | Overwrite existing files |
Get-FileHashChecksum of a file (verify downloads). Get-FileHash path [-Algorithm name]
| Parameter | What it does |
|---|---|
-Algorithm SHA256 | Default; also SHA1, SHA384, SHA512, MD5 |
(Get-FileHash f.iso).Hash -eq "ABC…" | Compare with the published hash |
Invoke-Itemalso: iiOpen something with its default program. Invoke-Item path
| Usage | What it does |
|---|---|
ii . | Open the current folder in Explorer |
ii report.pdf | Open a file |
ii *.txt | Open several files |
Where-Objectalso: where ?Filter objects in the pipeline. … | Where-Object { condition }
| Usage | What it does |
|---|---|
{ $_.Length -gt 1MB } | Script block: $_ is the current object |
Where-Object Status -eq Running | Short syntax for one comparison |
{ $_.Name -like "*.log" } | Wildcard match |
{ $_.Name -match "^\d+" } | Regex match |
{ $_.CPU -gt 10 -and $_.WS -gt 100MB } | Combine with -and / -or / -not |
.Where({ … }) | Faster method form on collections |
Select-Objectalso: selectPick properties or a number of objects. … | Select-Object [properties] [options]
| Parameter | What it does |
|---|---|
Name, Length | Only these properties |
-First 5 / -Last 5 | First / last items |
-Skip 10 | Skip items |
-Unique | Remove duplicates |
-ExpandProperty Name | Just the values (plain strings) |
-ExcludeProperty Id | Everything except some properties (with *) |
@{n='MB'; e={ $_.Length / 1MB }} | Calculated property |
Sort-Objectalso: sortSort objects. … | Sort-Object [property] [options]
| Parameter | What it does |
|---|---|
Length | Sort by a property |
-Descending | Biggest / newest first |
-Unique | Remove duplicates |
-Top 10 / -Bottom 10 | Only the first / last N (PowerShell 7) |
-CaseSensitive | Case-sensitive sort of strings |
@{e='Status'; d=$true}, Name | Several keys with their own direction |
Group-Objectalso: groupGroup objects and count them. … | Group-Object property [options]
| Parameter | What it does |
|---|---|
Extension | Group by a property (Count, Name, Group) |
-NoElement | Only the counts, not the items |
-AsHashTable | Return a hashtable ($h['.log']) |
-CaseSensitive | Case-sensitive grouping |
Measure-Objectalso: measureCount, sum, average. … | Measure-Object [property] [options]
| Parameter | What it does |
|---|---|
| (none) | Count the items |
Length -Sum | Total of a property (-Average, -Minimum, -Maximum) |
-AllStats | Every statistic (PowerShell 7) |
-Line -Word -Character | Text statistics |
ForEach-Objectalso: foreach %Run code for each object in the pipeline. … | ForEach-Object { … }
| Usage / parameter | What it does |
|---|---|
{ $_.Name.ToUpper() } | $_ is the current item |
-Begin { … } -Process { … } -End { … } | Code before / per item / after |
-MemberName Name | Shortcut: % Name returns each Name |
-Parallel { … } -ThrottleLimit 5 | Run in parallel (PowerShell 7) |
Format-Tablealso: ftShow output as a table. … | Format-Table [properties] [options]
| Parameter | What it does |
|---|---|
Name, Length | Choose columns |
-AutoSize | Fit column widths to the content |
-Wrap | Wrap long values instead of cutting them off |
-GroupBy Status | Separate tables per group |
-HideTableHeaders | No header row |
Format cmdlets are for display only: use them last in the pipeline.
Format-Listalso: flShow every property on its own line. … | Format-List [properties]
| Usage | What it does |
|---|---|
Format-List * | All properties (great for exploring objects) |
Format-List Name, Id | Only some |
Out-GridViewalso: ogvInteractive, sortable, filterable window (Windows). … | Out-GridView [options]
| Parameter | What it does |
|---|---|
-Title "Processes" | Window title |
-PassThru | Selected rows are passed on: ps | ogv -PassThru | Stop-Process |
-OutputMode Single | Allow selecting one row |
-Wait | Wait until the window is closed |
Built in on Windows (also PowerShell 7); on Linux/macOS use the Microsoft.PowerShell.ConsoleGuiTools module instead.
Export-Csvalso: epcsvSave objects as CSV. … | Export-Csv path [options]
| Parameter | What it does |
|---|---|
-NoTypeInformation | No #TYPE first line (default in PowerShell 7) |
-Delimiter ";" | Separator (; for Excel in Belgium/NL) |
-UseCulture | Use the system list separator |
-Append | Add to an existing file |
-Encoding utf8 | Encoding |
-Force | Overwrite read-only files |
Import-Csvalso: ipcsvRead a CSV file as objects. Import-Csv path [options]
| Parameter | What it does |
|---|---|
-Delimiter ";" | Separator |
-Header a,b,c | Column names when the file has none |
-Encoding utf8 | Encoding |
-UseCulture | Use the system list separator |
ConvertTo-Jsonalso: ConvertFrom-JsonConvert objects to / from JSON.
| Usage / parameter | What it does |
|---|---|
… | ConvertTo-Json | Objects → JSON text |
-Depth 5 | Nested levels to include (default 2!) |
-Compress | One line, no spaces |
-AsArray | Always output an array (PowerShell 7) |
Get-Content a.json -Raw | ConvertFrom-Json | JSON text → objects |
ConvertFrom-Json -AsHashtable | Hashtables instead of objects (PowerShell 7) |
Start-Processalso: start sapsStart a program, optionally as admin or in a new window. Start-Process file [options]
| Parameter | What it does |
|---|---|
-Verb RunAs | Run as administrator (UAC prompt) |
-ArgumentList "-a", "b" | Arguments for the program |
-WorkingDirectory C:\dev | Start folder |
-Wait | Wait until it exits |
-NoNewWindow | Use the current console |
-WindowStyle Hidden | Normal, Minimized, Maximized, Hidden |
-PassThru | Return the process object |
-RedirectStandardOutput out.txt | Save the output |
Start-Process https://github.com | Open a URL |
Get-Servicealso: gsvWindows services. Get-Service [name] [options]
| Parameter | What it does |
|---|---|
-Name wuauserv | By name (wildcards OK) |
-DisplayName "*Update*" | By display name |
-DependentServices | Services that depend on it |
-RequiredServices | Services it needs |
| Where Status -eq Running | Only running services |
Related: Start-Service, Stop-Service, Set-Service -StartupType Disabled.
Restart-ServiceRestart a Windows service (admin). Restart-Service name [options]
| Parameter | What it does |
|---|---|
-Name Spooler | Service name |
-Force | Also stop services that depend on it |
-PassThru | Output the service |
-WhatIf | Preview |
Test-ConnectionPing, PowerShell style. Test-Connection host [options]
| Parameter | What it does |
|---|---|
-Count 4 | Number of pings |
-Quiet | Just True / False |
-Repeat | Keep pinging (PowerShell 7) |
-TimeoutSeconds 2 | Timeout (PowerShell 7) |
-Traceroute | Trace the route (PowerShell 7) |
-TcpPort 443 | Test a TCP port (PowerShell 7) |
-BufferSize 1400 | Packet size |
Test-NetConnectionalso: tncTest ping, a port or the route to a host. Test-NetConnection host [options]
| Parameter | What it does |
|---|---|
-Port 443 | Is this TCP port open? (TcpTestSucceeded) |
-CommonTCPPort HTTP | HTTP, RDP, SMB, WINRM |
-TraceRoute | Show every hop |
-InformationLevel Detailed | More details (Quiet = just True/False) |
Resolve-DnsNameDNS lookup. Resolve-DnsName name [options]
| Parameter | What it does |
|---|---|
-Type MX | Record type: A, AAAA, MX, TXT, NS, CNAME… |
-Server 1.1.1.1 | Ask a specific DNS server |
-DnsOnly | Skip local names (hosts file, NetBIOS) |
-NoHostsFile | Ignore the hosts file |
Get-NetIPAddressIP addresses of this computer. Get-NetIPAddress [options]
| Parameter | What it does |
|---|---|
-AddressFamily IPv4 | Only IPv4 (IPv6) |
-InterfaceAlias "Wi-Fi" | One adapter |
-PrefixOrigin Dhcp | Only addresses from DHCP (Manual) |
| Format-Table InterfaceAlias, IPAddress | Compact overview |
Related: Get-NetAdapter, Get-NetIPConfiguration, Get-DnsClientServerAddress.
Invoke-WebRequestalso: iwr wget curlDownload files or fetch web pages. Invoke-WebRequest url [options]
| Parameter | What it does |
|---|---|
-OutFile file.zip | Save to a file |
-Method Post | HTTP method |
-Body '{"a":1}' | Request body |
-ContentType 'application/json' | Body type |
-Headers @{ Authorization = "Bearer $t" } | Extra headers |
-UseBasicParsing | No Internet Explorer parsing (Windows PowerShell) |
-SkipCertificateCheck | Ignore TLS errors (PowerShell 7, testing only) |
-TimeoutSec 10 | Timeout |
-MaximumRedirection 0 | Don't follow redirects |
In Windows PowerShell curl and wget are aliases for this cmdlet; type curl.exe for real curl.
Invoke-RestMethodalso: irmCall an API: JSON responses become objects automatically. Invoke-RestMethod url [options]
| Parameter | What it does |
|---|---|
-Method Post | Get, Post, Put, Patch, Delete |
-Body ($obj | ConvertTo-Json) | Send JSON |
-ContentType 'application/json' | Body type |
-Headers @{ Authorization = "Bearer $t" } | Headers |
-Authentication Bearer -Token $secure | Built-in auth (PowerShell 7) |
-OutFile result.json | Save the response |
-StatusCodeVariable code | Status code into $code (PowerShell 7) |
Nothing on this sheet matches “”.