⏳
Loading cheatsheet...
Cmdlets, pipelines, variables, modules, remoting, DSC, error handling, and automation scripts.
# ── Basic Cmdlets (Verb-Noun naming) ──
Get-Process # List processes
Get-Service # List services
Get-ChildItem -Path "C:\Temp" # List directory contents
Get-Content -Path "file.txt" # Read file contents
Get-Date # Current date/time
Get-History # Command history
Get-Alias grep # Find alias
# ── Filtering & Selection ──
Get-Process | Where-Object { $_.CPU -gt 10 }
Get-Process | Where-Object { $_.Name -like "*chrome*" }
Get-Process | Select-Object Name, CPU, WorkingSet -First 10
Get-Service | Where-Object Status -eq "Running"
Get-ChildItem -Filter "*.txt" -Recurse
# ── Sorting & Grouping ──
Get-Process | Sort-Object CPU -Descending
Get-Process | Group-Object -Property Name -NoElement
Get-ChildItem | Measure-Object -Property Length -Sum -Average
# ── Pipeline (| operator) ──
Get-Process | Where-Object {$_.WorkingSet -gt 100MB} |
Sort-Object CPU -Descending |
Select-Object Name, @{N="Memory(MB)";E={[math]::Round($_.WorkingSet/1MB)}} |
Format-Table -AutoSize
# ── Common Verbs ──
# Get, Set, New, Remove, Add, Clear, Export, Import
# Start, Stop, Restart, Suspend, Resume
# Find, Search, Select, Sort, Group, Measure, Format, Out, Write| Operator | Meaning |
|---|---|
| -eq / -ne | Equal / Not equal |
| -gt / -lt | Greater than / Less than |
| -ge / -le | Greater or equal / Less or equal |
| -like / -notlike | Wildcard match (*, ?) |
| -match / -notmatch | Regex match |
| -contains / -in | Contains in collection |
| -is / -isnot | Type checking |
| Cmdlet | Purpose |
|---|---|
| Format-Table | Tabular output |
| Format-List | List property output |
| Format-Wide | Wide multi-column |
| Out-File | Save to file |
| Out-GridView | GUI table viewer |
| Export-Csv | Export to CSV |
| ConvertTo-Json | Convert to JSON |
| ConvertFrom-Json | Parse JSON |
| Export-Clixml | Serialize to XML |
# ── Variables ──
$name = "John"
$age = 30
$isAdmin = $true
$pi = 3.14159
$null # Null value
$empty = ""
# String interpolation
"Hello, $name!" # Double quotes: variables expanded
'Hello, $name' # Single quotes: literal
"Value: $(1 + 1)" # Subexpression: $(...)
"Today is $(Get-Date -Format 'yyyy-MM-dd')"
# Multi-line string
$heredoc = @"
Line 1
Line 2: $name is $age years old
"@
# ── Arrays ──
$fruits = @("apple", "banana", "cherry")
$numbers = 1..10
$empty = @()
$fruits[0] # First item
$fruits[-1] # Last item
$fruits.Count # Length
$fruits += "date" # Append
$fruits -contains "apple"
# ── Hashtables ──
$user = @{
Name = "John"
Age = 30
Role = "admin"
Email = "john@example.com"
}
$user["Name"] # Access by key
$user.Name # Dot notation
$user.Keys # All keys
$user.Values # All values
# ── PSCustomObject ──
$record = [PSCustomObject]@{
Name = "John"
Department = "Engineering"
Salary = 85000
}
$record | Format-List
# ── Type Casting ──
[int]$num = "42"
[string]$str = 100
[bool]$flag = "true"
[int[]]$nums = @(1, 2, 3)| Scope | Description |
|---|---|
| $global: | Available everywhere |
| $script: | Current script file |
| $local: | Current scope only |
| $private: | Cannot be inherited by child scopes |
| $using: | C# using statement equivalent |
| Method | Example |
|---|---|
| .Split(",") | "a,b,c".Split(",") → array |
| .Join("-") | "a","b" -join "-" → "a-b" |
| .Replace("old","new") | "hello".Replace("l","L") |
| .Trim() | " hello ".Trim() → "hello" |
| .ToUpper() / .ToLower() | Case conversion |
| .Contains("str") | "hello".Contains("ell") |
| .StartsWith("str") | "hello".StartsWith("hel") |
| .Length | "hello".Length → 5 |
| .Substring(0,3) | "hello".Substring(0,3) → "hel" |
# ── Error Handling ──
try {
$content = Get-Content -Path "/nonexistent/file.txt" -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
Write-Host "File not found: $_" -ForegroundColor Red
}
catch {
Write-Host "Unexpected error: $_" -ForegroundColor Red
}
finally {
Write-Host "Cleanup complete" -ForegroundColor Green
}
# Error preference
$ErrorActionPreference = "Stop" # Stop on error (default Continue)
$ErrorActionPreference = "SilentlyContinue"
$ErrorActionPreference = "Inquire"
# ── Functions ──
function Get-Greeting {
param(
[Parameter(Mandatory)]
[string]$Name,
[int]$Age = 0,
[ValidateSet("Hello", "Hi", "Hey")]
[string]$Greeting = "Hello"
)
"$Greeting, $Name! You are $Age years old."
}
Get-Greeting -Name "John" -Age 30 -Greeting "Hi"
# Pipeline function (process block)
function Get-FileSize {
param([Parameter(ValueFromPipeline)]$Path)
process {
$item = Get-Item -Path $Path
[PSCustomObject]@{
File = $item.Name
Size = $item.Length
SizeKB = [math]::Round($item.Length / 1KB, 2)
}
}
}
Get-ChildItem "C:\Temp\*.txt" | Get-FileSize
# ── Modules ──
# List available modules
Get-Module -ListAvailable
Get-InstalledModule
# Install module (from PSGallery)
Install-Module -Name Pester -Scope CurrentUser
Install-Module -Name Az -Scope CurrentUser -Force
# Import module
Import-Module Pester
# Useful community modules
# Pester → Testing framework
# Az → Azure management
# dbatools → SQL Server
# ImportExcel → Excel files
# PSReadLine → Better console| Module | Purpose |
|---|---|
| Pester | Unit/integration testing |
| Az / AWS | Cloud resource management |
| PSReadLine | Enhanced console (syntax, autocomplete) |
| dbatools | SQL Server management |
| ImportExcel | Read/write Excel files |
| ThreadJob | Background jobs |
| Scoop | Package manager for Windows |
| Cmdlet | Purpose |
|---|---|
| Enter-PSSession | Interactive remote session |
| Invoke-Command | Run command on remote machine |
| New-PSSession | Create persistent connection |
| Copy-Item -ToSession | Copy files to remote session |
The pipeline (|) passes objects (not text) between cmdlets. Each cmdlet in the pipeline receives objects from the previous command via $_ (automatic variable) or $input. Objects flow through the pipeline as rich .NET objects with all their properties, not just string output. This enables powerful one-liner compositions like Get-Process | Where-Object {$_.CPU -gt 100} | Sort CPU -Desc.
Single quotes ('string') treat content as literal — no variable expansion, no expression evaluation. Double quotes ("string") expand variables ($var) and subexpressions ($(cmd)). Use single quotes for literal strings and double quotes when you need interpolation.