📖 Guide
PowerShell Cheat Sheet — Complete Reference
Every PowerShell cmdlet and pattern you need, from basic commands to scripting and remote management.
172 commands across 12 categories
Basic CommandsNavigation & FilesPipeline & FilteringString OperationsVariables & TypesControl FlowFunctionsError HandlingRemote ManagementProcesses & ServicesModules & PackagesCommon Aliases
Basic Commands
| Command | Description |
|---|---|
Get-Help <cmdlet>e.g. Get-Help Get-Process | Get help for a cmdlet |
Get-Help <cmdlet> -Examples | Show usage examples |
Get-Help <cmdlet> -Full | Show full help documentation |
Get-Command | List all available commands |
Get-Command -Name *process* | Find commands matching a pattern |
Get-Command -Module ActiveDirectory | List commands from a module |
Get-Alias | List all aliases |
Get-Alias -Name ls | Find what command an alias maps to |
Set-Alias -Name np -Value notepad | Create a custom alias |
Clear-Host | Clear the console (alias: cls) |
Write-Output 'Hello' | Write to output stream |
Write-Host 'Hello' -ForegroundColor Green | Write colored text to console |
$PSVersionTable | Show PowerShell version info |
Get-History | Show command history |
Navigation & Files
| Command | Description |
|---|---|
Get-Location | Show current directory (alias: pwd) |
Set-Location C:\Users | Change directory (alias: cd) |
Get-ChildItem | List directory contents (alias: ls, dir) |
Get-ChildItem -Recurse -Filter *.log | Find files recursively by pattern |
Get-ChildItem -Hidden | Show hidden files |
New-Item -ItemType File -Name test.txt | Create a new file |
New-Item -ItemType Directory -Name mydir | Create a new directory |
Copy-Item src.txt dest.txt | Copy a file (alias: cp, copy) |
Copy-Item -Recurse ./src ./dest | Copy directory recursively |
Move-Item old.txt new.txt | Move or rename file (alias: mv, move) |
Remove-Item file.txt | Delete a file (alias: rm, del) |
Remove-Item -Recurse -Force ./dir | Delete directory recursively |
Get-Content file.txt | Read file contents (alias: cat, type) |
Set-Content file.txt 'Hello' | Write string to file (overwrite) |
Add-Content file.txt 'More text' | Append to file |
Get-Content file.txt | Select-Object -First 10 | Show first 10 lines |
Get-Content file.txt -Tail 20 | Show last 20 lines |
Get-Content file.txt -Wait | Follow file in real-time (like tail -f) |
Test-Path ./file.txt | Check if file or path exists |
Resolve-Path ./relative | Resolve to absolute path |
Get-ItemProperty file.txt | Get file properties (size, dates, etc.) |
Pipeline & Filtering
| Command | Description |
|---|---|
Get-Process | Where-Object { $_.CPU -gt 100 } | Filter objects by condition |
Get-Service | Select-Object Name, Status | Select specific properties |
Get-Process | Sort-Object CPU -Descending | Sort by property |
Get-Process | Group-Object ProcessName | Group objects by property |
Get-Process | Measure-Object WorkingSet -Sum -Average | Calculate statistics |
Get-ChildItem | ForEach-Object { $_.Name } | Iterate over each object |
1..10 | ForEach-Object { $_ * 2 } | Transform each item |
Get-Process | Format-Table Name, CPU, WS -AutoSize | Display as formatted table |
Get-Process | Format-List * | Display all properties as list |
Get-Process | Out-File processes.txt | Write pipeline output to file |
Get-Process | Export-Csv procs.csv -NoTypeInformation | Export to CSV |
Import-Csv procs.csv | Import from CSV |
Get-Process | ConvertTo-Json | Convert to JSON |
Get-Content data.json | ConvertFrom-Json | Parse JSON |
Get-Process | Select-Object -First 5 | Take first 5 results |
Get-Process | Select-Object -Unique | Remove duplicates |
Get-Process | Tee-Object -FilePath log.txt | Output to both pipeline and file |
String Operations
| Command | Description |
|---|---|
"Hello $name" | String interpolation (double quotes) |
'Hello $name' | Literal string (no interpolation, single quotes) |
@"
Multi-line
string
"@ | Here-string (multi-line) |
"hello".ToUpper() | Convert to uppercase |
"HELLO".ToLower() | Convert to lowercase |
"hello world".Contains("world") | Check if string contains substring |
"hello world".Replace("world", "there") | Replace substring |
"hello world".Split(" ") | Split string into array |
" hello ".Trim() | Remove leading/trailing whitespace |
"hello" -match "^he" | Regex match (returns boolean) |
"hello" -replace "l+", "L" | Regex replace |
"hello".Substring(0, 3)e.g. hel | Extract substring |
-join ("a", "b", "c") | Join array into string |
"hello".Length | Get string length |
[string]::IsNullOrEmpty($str) | Check if null or empty |
Variables & Types
| Command | Description |
|---|---|
$name = 'Daniel' | Create a variable |
$num = 42 | Integer variable |
$arr = @(1, 2, 3) | Create an array |
$hash = @{ key = 'value'; num = 42 } | Create a hashtable |
$hash['key'] | Access hashtable value |
$hash.key | Access with dot notation |
$arr += 4 | Add element to array |
$arr.Count | Get array length |
$arr[0] | Access array element (0-indexed) |
$arr[-1] | Access last element |
$arr[1..3] | Array slice |
[int]$x = '42' | Type casting |
$x.GetType() | Get variable type |
$null | Null value |
$true / $false | Boolean values |
$env:PATH | Access environment variable |
$env:MY_VAR = 'value' | Set environment variable (session only) |
Get-Variable | List all variables |
Remove-Variable name | Delete a variable |
Control Flow
| Command | Description |
|---|---|
if ($x -eq 5) { ... } | If statement |
if ($x -gt 0) { ... } else { ... } | If-else |
if ($x -gt 0) { ... } elseif ($x -eq 0) { ... } | If-elseif-else |
-eq, -ne, -gt, -lt, -ge, -le | Comparison operators |
-and, -or, -not, ! | Logical operators |
-like 'test*' | Wildcard match |
-match '^\d+' | Regex match |
-contains 'item' | Array contains value |
-in @(1,2,3) | Value in array |
switch ($val) { 1 {'one'} 2 {'two'} default {'other'} } | Switch statement |
for ($i=0; $i -lt 10; $i++) { ... } | For loop |
foreach ($item in $collection) { ... } | Foreach loop |
while ($x -lt 10) { $x++ } | While loop |
do { ... } while ($x -lt 10) | Do-while loop |
1..10 | Range operator (generates 1 to 10) |
break | Exit loop |
continue | Skip to next iteration |
Functions
| Command | Description |
|---|---|
function Get-Greeting { 'Hello' } | Simple function |
function Add ($a, $b) { $a + $b } | Function with parameters |
function Test { param([string]$Name, [int]$Age) ... } | Typed parameters with param block |
param([Parameter(Mandatory)]$Name) | Make parameter mandatory |
param([ValidateSet('A','B')]$Option) | Validate parameter values |
param([string]$Name = 'Default') | Default parameter value |
return $result | Return value from function |
function Test { begin {...} process {...} end {...} } | Pipeline-aware function |
Get-Greeting | function | Functions receive pipeline input via $input or process block |
Error Handling
| Command | Description |
|---|---|
try { ... } catch { ... } | Try-catch block |
try { ... } catch { $_.Exception.Message } | Access error message |
try { ... } catch [System.IO.FileNotFoundException] { ... } | Catch specific exception type |
try { ... } finally { ... } | Finally block (always runs) |
$ErrorActionPreference = 'Stop' | Make all errors terminating |
-ErrorAction Stop | Make single command error terminating |
-ErrorAction SilentlyContinue | Suppress errors silently |
$Error[0] | Most recent error |
$Error.Clear() | Clear error history |
Write-Error 'Something failed' | Write an error to error stream |
throw 'Fatal error' | Throw a terminating error |
Remote Management
| Command | Description |
|---|---|
Enter-PSSession -ComputerName server1 | Start interactive remote session |
Exit-PSSession | Exit remote session |
Invoke-Command -ComputerName server1 -ScriptBlock { Get-Process } | Run command on remote machine |
Invoke-Command -ComputerName s1,s2,s3 -ScriptBlock { ... } | Run on multiple machines |
$session = New-PSSession -ComputerName server1 | Create persistent session |
Invoke-Command -Session $session -ScriptBlock { ... } | Run command in persistent session |
Copy-Item -ToSession $session -Path ./file -Destination C:\temp | Copy file to remote session |
Remove-PSSession $session | Close remote session |
Enable-PSRemoting -Force | Enable PowerShell remoting on machine |
Invoke-WebRequest -Uri 'https://api.example.com' | Make HTTP request (alias: curl, wget) |
Invoke-RestMethod -Uri 'https://api.example.com/data' | Make REST API call (auto-parse JSON) |
Processes & Services
| Command | Description |
|---|---|
Get-Process | List all running processes |
Get-Process -Name chrome | Get process by name |
Stop-Process -Name notepad | Kill process by name |
Stop-Process -Id 1234 -Force | Force kill by PID |
Start-Process notepad | Launch a program |
Start-Process cmd -ArgumentList '/c dir' -Wait | Start process with arguments |
Get-Service | List all services |
Get-Service -Name wuauserv | Get service by name |
Start-Service -Name wuauserv | Start a service |
Stop-Service -Name wuauserv | Stop a service |
Restart-Service -Name wuauserv | Restart a service |
Set-Service -Name svc -StartupType Automatic | Set service startup type |
Modules & Packages
| Command | Description |
|---|---|
Get-Module -ListAvailable | List all installed modules |
Import-Module ActiveDirectory | Import a module |
Install-Module -Name Az | Install module from PowerShell Gallery |
Update-Module -Name Az | Update installed module |
Uninstall-Module -Name OldModule | Remove a module |
Find-Module -Name *azure* | Search PowerShell Gallery |
Get-InstalledModule | List modules installed via Install-Module |
Install-Script -Name script-name | Install a script from Gallery |
Set-ExecutionPolicy RemoteSigned | Allow running local scripts |
Get-ExecutionPolicy | Check current execution policy |
Common Aliases
| Command | Description |
|---|---|
ls → Get-ChildItem | List directory |
cd → Set-Location | Change directory |
pwd → Get-Location | Print working directory |
cat → Get-Content | Read file |
cp → Copy-Item | Copy file |
mv → Move-Item | Move/rename |
rm → Remove-Item | Delete |
echo → Write-Output | Print output |
cls → Clear-Host | Clear screen |
where → Where-Object | Filter pipeline |
select → Select-Object | Select properties |
sort → Sort-Object | Sort pipeline |
% → ForEach-Object | Iterate pipeline |
? → Where-Object | Filter (shorthand) |
curl → Invoke-WebRequest | HTTP request |
wget → Invoke-WebRequest | Download |
📖 Free, searchable command reference. Bookmark this page for quick access.