Shell & Scripting18 min
PowerShell — Essential Commands Cheat Sheet
Core PowerShell reference — cmdlets, pipelines, file ops, remoting, error handling, and scripting patterns for Windows and cross-platform automation.
Help & Discovery
Get-Command # List all commands
Get-Command *-Process # Filter by name pattern
Get-Help Get-Process # Help for a command
Get-Help Get-Process -Examples # Show examples
Get-Help Get-Process -Full # Full documentation
Update-Help # Update local help database
Get-Member # Show object properties/methods
Get-Process | Get-Member # Properties of Process objects
Navigation & File System
Get-Location # pwd
Set-Location C:\Users\user\projects # cd
Set-Location ~ # Home directory
Push-Location C:\temp # Push and cd
Pop-Location # Return to pushed location
Get-ChildItem # ls / dir
Get-ChildItem -Recurse -Filter *.log # Recursive filter
Get-ChildItem -File -Recurse | Where-Object { $_.Length -gt 1MB }
File Operations
# Create
New-Item -ItemType File -Path file.txt
New-Item -ItemType Directory -Path mydir -Force
# Copy / Move
Copy-Item src.txt dest.txt
Copy-Item -Recurse ./src ./dest
Move-Item old.txt new.txt
# Delete
Remove-Item file.txt
Remove-Item -Recurse -Force ./dir
# Read / Write
Get-Content file.txt # cat
Get-Content file.txt | Select-Object -First 20 # head
Add-Content file.txt "new line" # append
Set-Content file.txt "replace all" # overwrite
$data = Get-Content file.txt # store lines as array
Pipelines & Filtering
# Pipeline basics
Get-Process | Where-Object { $_.CPU -gt 10 }
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10
Get-Service | Where-Object { $_.Status -eq 'Running' }
# Select properties
Get-Process | Select-Object Name, CPU, WorkingSet
Get-Process | Select-Object -ExpandProperty Name # just values
# Format output
Get-Process | Format-Table Name, CPU, Id
Get-Process | Format-List * # all properties as list
Get-Process | Out-GridView # interactive GUI grid (Windows)
# Export
Get-Process | Export-Csv processes.csv -NoTypeInformation
Get-Process | ConvertTo-Json | Out-File processes.json
Import-Csv data.csv
Variables & Data Types
$name = "Alice"
$num = 42
$pi = 3.14
$flag = $true
# Arrays
$arr = @(1, 2, 3, "four")
$arr += 5
$arr[0] # first element
$arr[-1] # last element
$arr.Count # length
# Hashtables (dictionaries)
$hash = @{ name = "Alice"; age = 30 }
$hash["name"] # access
$hash.name # dot notation
$hash.Keys
$hash.Values
$hash.Remove("age")
# String interpolation
"Hello, $name!" # simple
"Result: $($num * 2)" # expression in string
Conditionals & Loops
# if / elseif / else
if ($x -gt 10) { "big" }
elseif ($x -eq 10) { "ten" }
else { "small" }
# Comparison operators
-eq -ne -gt -lt -ge -le # numbers
-like -notlike # wildcards: "*.txt"
-match -notmatch # regex
-contains -notcontains # array membership
# for / foreach
for ($i = 0; $i -lt 10; $i++) { Write-Host $i }
foreach ($item in $arr) { Write-Host $item }
1..10 | ForEach-Object { Write-Host $_ }
# while
$i = 0
while ($i -lt 5) { Write-Host $i; $i++ }
Functions
function Get-Greeting {
param(
[Parameter(Mandatory)]
[string]$Name,
[string]$Greeting = "Hello"
)
return "$Greeting, $Name!"
}
Get-Greeting -Name "Alice" # Hello, Alice!
Get-Greeting -Name "Bob" -Greeting "Hi" # Hi, Bob!
Error Handling
# Try / Catch / Finally
try {
Get-Content "nonexistent.txt" -ErrorAction Stop
} catch [System.IO.FileNotFoundException] {
Write-Error "File not found: $_"
} catch {
Write-Error "Unexpected error: $_"
} finally {
Write-Host "Cleanup here"
}
# Error preference
$ErrorActionPreference = "Stop" # throw on any error
$ErrorActionPreference = "Continue" # default
# Suppress errors
Get-Item "missing.txt" -ErrorAction SilentlyContinue
Remoting & Execution
# Run command on remote machine
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Process }
# Interactive session
Enter-PSSession -ComputerName server01
# Run script
Invoke-Command -ComputerName server01 -FilePath .\script.ps1
# Execution policy
Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned # Allow local + signed remote scripts
Set-ExecutionPolicy Bypass -Scope Process # Just for current session
String Manipulation
$s = " Hello World "
$s.Trim() # "Hello World"
$s.ToLower() # " hello world "
$s.ToUpper() # " HELLO WORLD "
$s.Replace("World", "PS") # " Hello PS "
$s.Split(" ") # array of words
$s.Contains("World") # True
$s.StartsWith(" Hello") # True
$s.Substring(2, 5) # "Hello"
$s -match "Hello\s(\w+)" # regex match; $Matches[1] = "World"
-join ("a", "b", "c") # "abc"
"a","b","c" -join "-" # "a-b-c"
Useful Patterns
# Measure execution time
Measure-Command { Start-Sleep -Seconds 2 }
# Find processes by name
Get-Process -Name *chrome* | Stop-Process -WhatIf
# Check if running as admin
([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
# Load a module
Import-Module Az
Get-Module -ListAvailable Az*
# Environment variables
$env:PATH
$env:USERNAME
[System.Environment]::GetEnvironmentVariable("PATH", "Machine")
[System.Environment]::SetEnvironmentVariable("MY_VAR", "value", "User")
# Base64
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello"))
$decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))
Key Aliases
| Alias | Cmdlet |
|---|---|
ls / dir / gci | Get-ChildItem |
cd / sl | Set-Location |
cat / gc | Get-Content |
rm / del | Remove-Item |
cp | Copy-Item |
mv | Move-Item |
echo / write | Write-Output |
ps / gps | Get-Process |
kill | Stop-Process |
man | Get-Help |
% | ForEach-Object |
? | Where-Object |
