PowerShell is the command line shell and scripting language built into Windows (and available cross platform via PowerShell 7+). This cheat sheet covers the co…
PowerShell is the command-line shell and scripting language built into Windows (and available cross-platform via PowerShell 7+). This cheat sheet covers the commands, syntax, and patterns you'll actually use — whether you're managing files, automating admin tasks, or writing full scripts. Bookmark it for quick reference.
Table of Contents
- Getting Started
- Core Concepts
- Getting Help
- File System Navigation
- File & Folder Operations
- Working with Output & Objects
- Variables & Data Types
- Operators
- Arrays & Hashtables
- String Manipulation
- Conditionals & Loops
- Functions
- Pipeline & Filtering
- Working with Processes & Services
- Networking Commands
- Working with Files (CSV, JSON, XML)
- Remoting
- Modules & Packages
- Error Handling
- Execution Policy & Security
- Aliases Cheat List
- Common Errors & Fixes
- Pro Tips
Getting Started
Core Concepts
- PowerShell commands are called cmdlets, following a
Verb-Noun naming pattern (e.g., Get-Process, Set-Location, New-Item).
- Unlike traditional shells, PowerShell passes objects through the pipeline, not plain text — this is its biggest advantage.
- Common approved verbs:
Get, Set, New, Remove, Start, Stop, Add, Clear, Copy, Move, Test, Invoke, Import, Export.
- List all available verbs:
Get-Verb
Getting Help
Get-Help Get-Process # Basic help for a cmdlet
Get-Help Get-Process -Full # Full help with all parameters
Get-Help Get-Process -Examples # Just usage examples
Get-Help Get-Process -Online # Opens the online documentation
Update-Help # Downloads/refreshes the local help files
Get-Command # Lists all available commands
Get-Command *service* # Search commands by keyword
Get-Member # Shows properties/methods of a piped object
# Example: discover what a returned object can do
Get-Process | Get-Member
File System Navigation
Get-Location # Show current directory (alias: pwd)
Set-Location C:\Projects # Change directory (alias: cd)
Get-ChildItem # List files/folders (alias: ls, dir)
Get-ChildItem -Recurse # List recursively
Get-ChildItem -Force # Include hidden/system files
Push-Location / Pop-Location # Save and return to a previous location
Resolve-Path .\file.txt # Get the full path of a relative path
File & Folder Operations
New-Item -Path "C:\Projects\notes.txt" -ItemType File
New-Item -Path "C:\Projects\NewFolder" -ItemType Directory
Copy-Item "source.txt" "destination.txt"
Copy-Item "C:\Source" "C:\Dest" -Recurse
Move-Item "old\path\file.txt" "new\path\file.txt"
Rename-Item "old.txt" "new.txt"
Remove-Item "file.txt"
Remove-Item "Folder" -Recurse -Force
Test-Path "C:\Projects" # Returns True/False if path exists
Get-Content "file.txt" # Read file contents (alias: cat, type)
Set-Content "file.txt" "Hello" # Overwrite file contents
Add-Content "file.txt" "More text" # Append to a file
Working with Output & Objects
Get-Process | Select-Object Name, CPU, Id # Choose specific properties
Get-Process | Sort-Object CPU -Descending # Sort results
Get-Process | Where-Object { $_.CPU -gt 100 } # Filter results
Get-Process | Format-Table -AutoSize # Table output
Get-Process | Format-List # Detailed list output
Get-Process | Measure-Object # Count/sum/average objects
Get-Process | ConvertTo-Json # Convert output to JSON
Get-Process | Export-Csv processes.csv -NoTypeInformation
Variables & Data Types
$name = "Michael" # String
$age = 30 # Integer
$price = 19.99 # Double
$isActive = $true # Boolean
$today = Get-Date # DateTime object
$null # Null value
$name.GetType() # Check a variable's type
[int]$count = "5" # Explicit type casting
[string]$text = 42
Special/automatic variables:
$_ # Current object in the pipeline
$Args # Arguments passed to a script/function
$Error # Array of recent errors
$Home # Current user's home directory
$PSVersionTable # PowerShell version info
$true / $false / $null
Operators
# Comparison
-eq # equal
-ne # not equal
-gt # greater than
-lt # less than
-ge # greater than or equal
-le # less than or equal
-like # wildcard string match
-notlike
-match # regex match
-contains # collection contains value
# Logical
-and
-or
-not / !
# Arithmetic
+ - * / %
# Assignment
= += -= *= /=
Note: PowerShell comparison operators are text-based (-eq, -gt) rather than symbols (==, >) — this avoids conflicts with redirection symbols.
Arrays & Hashtables
# Arrays
$fruits = @("Apple", "Banana", "Mango")
$fruits[0] # Access by index
$fruits += "Orange" # Add an item
$fruits.Count # Number of items
foreach ($f in $fruits) { Write-Output $f }
# Hashtables (key-value pairs)
$person = @{ Name = "Michael"; Age = 30; Country = "Kenya" }
$person["Name"] # Access a value
$person.Age # Dot notation also works
$person["Email"] = "m@x.com" # Add/update a key
$person.Remove("Age") # Remove a key
String Manipulation
$s = "Hello, World!"
$s.Length # String length
$s.ToUpper() / $s.ToLower() # Case conversion
$s.Substring(0,5) # "Hello"
$s.Replace("World","Kenya") # Replace text
$s.Split(",") # Split into an array
$s.Trim() # Remove leading/trailing whitespace
$s -match "World" # Regex match (returns True/False)
$s.Contains("World") # Simple substring check
# String formatting
"$name is $age years old" # Variable interpolation (double quotes only)
"{0} is {1} years old" -f $name, $age # -f format operator
Conditionals & Loops
# If / elseif / else
if ($age -ge 18) {
Write-Output "Adult"
} elseif ($age -ge 13) {
Write-Output "Teenager"
} else {
Write-Output "Child"
}
# Switch
switch ($day) {
"Mon" { "Start of week" }
"Fri" { "Almost weekend" }
default { "Midweek" }
}
# For loop
for ($i = 0; $i -lt 5; $i++) { Write-Output $i }
# Foreach loop
foreach ($item in $fruits) { Write-Output $item }
# While loop
$i = 0
while ($i -lt 5) { $i++; Write-Output $i }
# Do-While
do { $i++ } while ($i -lt 5)
Functions
function Get-Square {
param(
[int]$Number
)
return $Number * $Number
}
Get-Square -Number 5 # Call the function → returns 25
# Function with multiple typed parameters and a default value
function Greet-User {
param(
[string]$Name,
[int]$Age = 18
)
Write-Output "Hello $Name, you are $Age years old."
}
Pipeline & Filtering
Get-Process | Where-Object { $_.CPU -gt 50 } | Sort-Object CPU -Descending
Get-ChildItem *.log | ForEach-Object { Remove-Item $_.FullName }
Get-Service | Where-Object Status -eq "Running"
1..10 | ForEach-Object { $_ * 2 } # Pipe a range and transform each item
Where-Object and ForEach-Object are the two cmdlets you'll reach for constantly — they're the PowerShell equivalents of a filter and a map function.
Working with Processes & Services
Get-Process # List running processes
Get-Process notepad # Find a specific process
Stop-Process -Name "notepad" # Kill a process by name
Stop-Process -Id 1234 # Kill a process by ID
Get-Service # List all services
Get-Service -Name "wuauserv" # Find a specific service
Start-Service "wuauserv"
Stop-Service "wuauserv"
Restart-Service "wuauserv"
Networking Commands
Test-Connection google.com # Like ping
Test-NetConnection google.com -Port 443 # Test a specific port
Resolve-DnsName google.com # DNS lookup
Get-NetIPAddress # Show local IP configuration
Get-NetAdapter # List network adapters
Invoke-WebRequest https://example.com # Fetch a web page/API
Invoke-RestMethod https://api.example.com/data # Call a REST API and parse JSON automatically
Working with Files (CSV, JSON, XML)
# CSV
Import-Csv "data.csv"
Export-Csv "data.csv" -NoTypeInformation
# JSON
$json = Get-Content "data.json" | ConvertFrom-Json
$obj | ConvertTo-Json -Depth 5 | Set-Content "output.json"
# XML
[xml]$xml = Get-Content "data.xml"
$xml.root.item
Remoting
Enable-PSRemoting -Force # Enable remoting on a machine
Test-WSMan computername # Test if remoting is available
Invoke-Command -ComputerName Server01 -ScriptBlock { Get-Process }
Enter-PSSession -ComputerName Server01 # Open an interactive remote session
Exit-PSSession # Close the remote session
Modules & Packages
Get-Module -ListAvailable # List installed modules
Import-Module ActiveDirectory # Load a module into the session
Install-Module -Name Az # Install a module from PowerShell Gallery
Find-Module -Name "*sql*" # Search the gallery
Uninstall-Module -Name Az # Remove a module
Error Handling
try {
Get-Item "C:\DoesNotExist.txt" -ErrorAction Stop
} catch {
Write-Output "Error occurred: $_"
} finally {
Write-Output "Cleanup runs regardless of outcome"
}
# Common -ErrorAction values
-ErrorAction Stop # Turns a non-terminating error into a terminating one (needed for try/catch)
-ErrorAction SilentlyContinue # Suppresses the error
-ErrorAction Continue # Default — shows error, keeps going
Execution Policy & Security
Get-ExecutionPolicy # Check current policy
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser # Allow local scripts, require signed remote scripts
Set-ExecutionPolicy Restricted # Blocks all scripts (default on some systems)
Unblock-File .\script.ps1 # Remove the "downloaded from internet" flag
Note: Execution policy is a safety guardrail, not a full security boundary — it can be bypassed by a determined user with local access. Don't rely on it alone in a security-sensitive environment.
Aliases Cheat List
| Alias |
Full Cmdlet |
ls / dir |
Get-ChildItem |
cd |
Set-Location |
pwd |
Get-Location |
cat / type |
Get-Content |
cp |
Copy-Item |
mv |
Move-Item |
rm / del |
Remove-Item |
ps |
Get-Process |
kill |
Stop-Process |
echo |
Write-Output |
cls / clear |
Clear-Host |
gm |
Get-Member |
select |
Select-Object |
where / ? |
Where-Object |
foreach / % |
ForEach-Object |
sort |
Sort-Object |
Common Errors & Fixes
| Error |
Likely Cause |
Fix |
| "running scripts is disabled on this system" |
Execution policy blocks scripts |
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser |
| "is not recognized as the name of a cmdlet" |
Typo, or module not imported |
Check spelling; Import-Module the required module |
| "Access is denied" |
Insufficient privileges |
Re-run PowerShell as Administrator |
| Script runs but does nothing visible |
Missing Write-Output / output not returned |
Explicitly output results, or check for a trailing ` |
Variable shows empty/$null unexpectedly |
Scope issue (variable set inside a function/loop isn't visible outside) |
Use $script: or $global: scope modifiers, or return the value explicitly |
| CSV/JSON import looks wrong |
Delimiter or encoding mismatch |
Check -Delimiter parameter on Import-Csv, or file encoding |
Pro Tips
- Use
Get-Command, Get-Help, and Get-Member as your three best friends when exploring anything unfamiliar — you rarely need to leave the shell to look something up.
- Prefer full cmdlet names (
Get-ChildItem) over aliases (ls) in scripts you'll share or maintain — aliases are fine interactively, but hurt readability in saved scripts.
- Use
-WhatIf on destructive cmdlets (Remove-Item -WhatIf) to preview what would happen before actually running it.
- Use
ISE or VS Code with the PowerShell extension for writing longer scripts — much easier than the raw console.
- Store reusable functions in a PowerShell profile (
$PROFILE) so they're available every time you open a new session.
- Use
Invoke-RestMethod instead of Invoke-WebRequest when working with JSON APIs — it parses the response for you automatically.
Got a PowerShell trick that saves you time? Share it in the comments below.