Files
TestRepo/PowerShell_Cheat_Sheet.md
2026-03-11 11:02:01 +00:00

17 KiB

Windows PowerShell Cheat Sheet

A practical reference guide for new and intermediate PowerShell users.


Table of Contents

  1. Getting Started
  2. Core Concepts
  3. Navigation & File System
  4. File & Folder Management
  5. Working with Text & Output
  6. Processes & Services
  7. Networking
  8. User & System Info
  9. Variables & Data Types
  10. Piping & Filtering
  11. Loops & Conditionals
  12. Functions & Scripts
  13. Error Handling
  14. Useful Tips & Tricks
  15. Common Aliases

Getting Started

Launching PowerShell

Method Notes
Win + X → Windows Terminal Recommended on Windows 10/11
Search "PowerShell" in Start Right-click → Run as Administrator for elevated tasks
pwsh in Run dialog Opens PowerShell 7+ if installed

Check Your Version

$PSVersionTable
$PSVersionTable.PSVersion

Get Help

Get-Help <cmdlet>              # Basic help
Get-Help <cmdlet> -Detailed    # More detail with examples
Get-Help <cmdlet> -Examples    # Examples only
Get-Help <cmdlet> -Online      # Opens Microsoft docs in browser
Update-Help                    # Downloads latest help files (run as Admin)

Discover Commands

Get-Command                        # List all available commands
Get-Command -Verb Get              # All cmdlets that start with 'Get'
Get-Command -Noun Service          # All cmdlets related to 'Service'
Get-Command *firewall*             # Wildcard search

Core Concepts

Verb-Noun Naming Convention

PowerShell cmdlets follow a Verb-Noun pattern. Common verbs:

Verb Purpose
Get Retrieve information
Set Change/configure something
New Create something new
Remove Delete something
Start / Stop Start or stop a process/service
Enable / Disable Toggle a feature
Invoke Run a command or expression
Export / Import Move data in/out

Objects, Not Text

PowerShell outputs objects, not plain text. This means you can access properties directly:

$process = Get-Process notepad
$process.Name       # "notepad"
$process.Id         # Process ID number
$process.CPU        # CPU usage

Navigation & File System

Basic Navigation

Get-Location          # Show current directory (like 'pwd')
Set-Location C:\      # Change directory (like 'cd')
Set-Location ..       # Go up one level
Set-Location ~        # Go to home directory
Push-Location C:\Temp # Save current location and navigate
Pop-Location          # Return to saved location

Listing Contents

Get-ChildItem                        # List files/folders (like 'ls' or 'dir')
Get-ChildItem -Force                 # Include hidden files
Get-ChildItem *.log                  # Filter by extension
Get-ChildItem -Recurse               # Recurse into subfolders
Get-ChildItem -Recurse -Filter *.txt # Recursive search for .txt files
Get-ChildItem | Sort-Object Length   # Sort by file size

Useful Shortcuts

# Tab completion — press Tab to autocomplete paths and cmdlet names
# Ctrl+R         — reverse search command history
# F7             — show command history in a popup window
# Up/Down arrows — cycle through previous commands

File & Folder Management

Create

New-Item -Path "C:\Temp\test.txt" -ItemType File
New-Item -Path "C:\Temp\NewFolder" -ItemType Directory
New-Item -Path "C:\Temp\test.txt" -ItemType File -Force  # Overwrite if exists

Copy, Move, Rename

Copy-Item "C:\source.txt" "C:\dest.txt"
Copy-Item "C:\SourceFolder" "C:\DestFolder" -Recurse   # Copy entire folder
Move-Item "C:\old.txt" "C:\new.txt"
Rename-Item "C:\oldname.txt" "newname.txt"

Delete

Remove-Item "C:\Temp\test.txt"
Remove-Item "C:\Temp\OldFolder" -Recurse               # Delete folder and contents
Remove-Item "C:\Temp\*.log"                             # Delete all .log files
Remove-Item "C:\Temp\test.txt" -WhatIf                  # Preview — does NOT delete

⚠️ Tip: Always use -WhatIf first to preview what a destructive command will do before running it.

Read & Write Files

Get-Content "C:\log.txt"                        # Read file contents
Get-Content "C:\log.txt" -Tail 20               # Last 20 lines (like 'tail')
Set-Content "C:\out.txt" "Hello, World!"        # Write (overwrites file)
Add-Content "C:\out.txt" "New line"             # Append to file
"Some text" | Out-File "C:\out.txt"             # Write via pipe
"More text" | Out-File "C:\out.txt" -Append     # Append via pipe

Working with Text & Output

Formatting Output

Get-Process | Format-Table                   # Table view
Get-Process | Format-Table -AutoSize         # Auto-fit columns
Get-Process | Format-List                    # Detailed list view
Get-Process | Format-List *                  # Show ALL properties
Get-Process | Out-GridView                   # Interactive GUI grid (Windows only)

Selecting & Filtering

Get-Process | Select-Object Name, CPU, Id          # Select specific columns
Get-Process | Select-Object -First 5               # First 5 results
Get-Process | Where-Object { $_.CPU -gt 10 }       # Filter by condition
Get-Service | Where-Object { $_.Status -eq "Running" }

Sorting

Get-Process | Sort-Object CPU                      # Sort ascending
Get-Process | Sort-Object CPU -Descending          # Sort descending
Get-Process | Sort-Object CPU | Select-Object -Last 10  # Top 10 by CPU

String Operations

"Hello World".ToLower()           # hello world
"Hello World".ToUpper()           # HELLO WORLD
"Hello World".Replace("World","PS")  # Hello PS
"Hello World".Split(" ")          # Split into array
"  trim me  ".Trim()              # Remove whitespace
"Hello" -like "*ell*"             # Wildcard match (True)
"Hello" -match "^H"               # Regex match (True)

Output to File

Get-Process | Out-File "C:\processes.txt"
Get-Process | Export-Csv "C:\processes.csv" -NoTypeInformation
Get-Service | ConvertTo-Json | Out-File "C:\services.json"

Processes & Services

Processes

Get-Process                                # List all running processes
Get-Process notepad                        # Find specific process by name
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10  # Top CPU users
Start-Process notepad                      # Launch an application
Stop-Process -Name notepad                 # Kill by name
Stop-Process -Id 1234                      # Kill by PID
Stop-Process -Name notepad -Force          # Force kill

Services

Get-Service                                # List all services
Get-Service -Name "wuauserv"               # Windows Update service
Get-Service | Where-Object {$_.Status -eq "Stopped"}  # Stopped services
Start-Service -Name "Spooler"              # Start a service
Stop-Service -Name "Spooler"               # Stop a service
Restart-Service -Name "Spooler"            # Restart a service
Set-Service -Name "Spooler" -StartupType Automatic  # Change startup type

Networking

Network Info

Get-NetIPAddress                           # All IP addresses
Get-NetIPAddress -AddressFamily IPv4       # IPv4 only
Get-NetAdapter                             # Network adapters
Get-NetAdapter | Where-Object {$_.Status -eq "Up"}  # Active adapters
Get-DnsClientServerAddress                 # DNS server settings

Connectivity & Testing

Test-Connection google.com                 # Ping (returns objects)
Test-Connection google.com -Count 4        # Ping 4 times
Test-NetConnection google.com -Port 443    # Test TCP port connectivity
Resolve-DnsName google.com                 # DNS lookup

Firewall

Get-NetFirewallRule | Where-Object {$_.Enabled -eq "True"}   # Active rules
Get-NetFirewallRule -DisplayName "*Remote*"                   # Search rules

User & System Info

System Information

Get-ComputerInfo                           # Detailed system info
Get-ComputerInfo | Select-Object CsName, WindowsVersion, OsArchitecture
[System.Environment]::OSVersion           # OS version
Get-HotFix                                # Installed Windows patches
Get-HotFix | Sort-Object InstalledOn -Descending  # Most recent first

Disk & Hardware

Get-PSDrive                                # All drives and free space
Get-Volume                                 # Disk volumes
Get-PhysicalDisk                           # Physical disks
Get-Disk                                   # Disk info

Users & Groups

Get-LocalUser                              # Local user accounts
Get-LocalGroup                             # Local groups
Get-LocalGroupMember Administrators        # Members of Administrators group
whoami                                     # Current user
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name  # Full username

Environment Variables

$env:USERNAME          # Current user
$env:COMPUTERNAME      # Machine name
$env:PATH              # System PATH
$env:TEMP              # Temp folder
Get-ChildItem Env:     # List all environment variables
$env:PATH += ";C:\MyTools"  # Temporarily add to PATH

Variables & Data Types

Declaring Variables

$name = "Alice"
$count = 42
$pi = 3.14159
$isAdmin = $true
$nothing = $null

# Strongly typed
[string]$text = "Hello"
[int]$number = 100
[bool]$flag = $false
[array]$items = @(1, 2, 3)
[hashtable]$map = @{ Key = "Value"; Name = "Test" }

Arrays

$fruits = @("Apple", "Banana", "Cherry")
$fruits[0]                   # "Apple"
$fruits[-1]                  # "Cherry" (last item)
$fruits.Count                # 3
$fruits += "Date"            # Add item
$fruits | ForEach-Object { Write-Host $_ }  # Iterate

Hash Tables (Dictionaries)

$person = @{
    Name = "Alice"
    Age  = 30
    City = "Melbourne"
}
$person["Name"]              # "Alice"
$person.Name                 # "Alice" (dot notation)
$person["Email"] = "a@b.com" # Add/update key
$person.Keys                 # List all keys
$person.Values               # List all values

Piping & Filtering

The pipeline (|) passes the output of one command as input to the next.

# Basic pipe
Get-Process | Stop-Process

# Filter with Where-Object (alias: '?')
Get-Service | Where-Object { $_.Status -eq "Running" }
Get-Service | ? { $_.StartType -eq "Automatic" }

# Select properties with Select-Object (alias: 'select')
Get-Process | Select-Object Name, Id, CPU

# ForEach-Object (alias: '%') — run a block for each item
Get-Service | ForEach-Object { Write-Host $_.Name }
1..10 | ForEach-Object { $_ * 2 }

# Measure
Get-ChildItem C:\Windows | Measure-Object               # Count items
Get-ChildItem C:\Windows -Recurse | Measure-Object Length -Sum  # Total size

Loops & Conditionals

If / ElseIf / Else

$x = 10

if ($x -gt 10) {
    Write-Host "Greater"
} elseif ($x -eq 10) {
    Write-Host "Equal"
} else {
    Write-Host "Less"
}

Comparison Operators

Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-lt Less than
-ge Greater than or equal
-le Less than or equal
-like Wildcard match
-match Regex match
-in Value exists in array
-contains Array contains value
-and Logical AND
-or Logical OR
-not Logical NOT

ForEach Loop

$servers = @("Server01", "Server02", "Server03")

foreach ($server in $servers) {
    Write-Host "Pinging $server..."
    Test-Connection $server -Count 1 -Quiet
}

For Loop

for ($i = 0; $i -lt 5; $i++) {
    Write-Host "Iteration $i"
}

While Loop

$count = 0
while ($count -lt 5) {
    Write-Host $count
    $count++
}

Switch Statement

$status = "Running"

switch ($status) {
    "Running"  { Write-Host "Service is active" }
    "Stopped"  { Write-Host "Service is stopped" }
    default    { Write-Host "Unknown status" }
}

Functions & Scripts

Writing a Function

function Get-DiskFreeSpace {
    param (
        [string]$DriveLetter = "C"
    )

    $drive = Get-PSDrive -Name $DriveLetter
    $freeGB = [math]::Round($drive.Free / 1GB, 2)
    Write-Host "$DriveLetter drive has $freeGB GB free"
}

# Call it
Get-DiskFreeSpace
Get-DiskFreeSpace -DriveLetter "D"

Script Parameters (at top of .ps1 file)

param (
    [Parameter(Mandatory=$true)]
    [string]$ServerName,

    [int]$Timeout = 30,

    [switch]$Verbose
)

Write-Host "Connecting to $ServerName with timeout $Timeout..."

Running Scripts

.\MyScript.ps1                           # Run script in current directory
.\MyScript.ps1 -ServerName "Server01"    # Pass parameters
. .\MyScript.ps1                         # Dot-source (loads functions into session)

Execution Policy

Get-ExecutionPolicy                       # Check current policy
Set-ExecutionPolicy RemoteSigned          # Allow local scripts (run as Admin)
Set-ExecutionPolicy Bypass -Scope Process # Bypass for current session only

⚠️ Note: Never set execution policy to Unrestricted in production environments.


Error Handling

Try / Catch / Finally

try {
    $result = Get-Content "C:\nonexistent.txt" -ErrorAction Stop
    Write-Host "Success: $result"
}
catch {
    Write-Host "Error: $($_.Exception.Message)"
}
finally {
    Write-Host "This always runs"
}

ErrorAction Parameter

# Control how cmdlets respond to errors
Get-Item "badpath" -ErrorAction SilentlyContinue  # Suppress error
Get-Item "badpath" -ErrorAction Stop              # Turn error into terminating
Get-Item "badpath" -ErrorAction Continue          # Default — show error, keep going

$Error Variable

$Error[0]              # Most recent error
$Error[0].Exception    # Exception details
$Error.Clear()         # Clear error history

Useful Tips & Tricks

Multi-Line Commands

# Use backtick ` to continue on next line
Get-Process `
    | Where-Object { $_.CPU -gt 5 } `
    | Sort-Object CPU -Descending `
    | Select-Object -First 10

Here-Strings (multi-line text)

$text = @"
This is line one
This is line two
Server: $env:COMPUTERNAME
"@

Measure Script Performance

Measure-Command { Get-Process | Sort-Object CPU }

Quick Calculations

[math]::Round(3.14159, 2)      # 3.14
[math]::Sqrt(144)              # 12
1GB / 1MB                      # 1024 (PowerShell understands KB, MB, GB, TB)
"{0:N2}" -f 1234567.89         # "1,234,567.89" (formatted number)

Clipboard

Get-Process | Clip                   # Copy output to clipboard
Set-Clipboard "text to copy"         # Copy text to clipboard
Get-Clipboard                        # Paste from clipboard

Scheduled Tasks (Quick Reference)

Get-ScheduledTask                             # List all tasks
Get-ScheduledTask -TaskName "MyTask"          # Specific task
Start-ScheduledTask -TaskName "MyTask"        # Run immediately
Disable-ScheduledTask -TaskName "MyTask"      # Disable task

Registry

Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"

Common Aliases

PowerShell includes many short aliases for common cmdlets. Useful to know, but avoid aliases in scripts — use full cmdlet names for readability.

Alias Full Cmdlet
ls / dir / gci Get-ChildItem
cd / sl Set-Location
pwd / gl Get-Location
cls / clear Clear-Host
cp / copy Copy-Item
mv / move Move-Item
rm / del / ri Remove-Item
cat / gc Get-Content
echo / write Write-Output
ps / gps Get-Process
kill Stop-Process
man / help Get-Help
? Where-Object
% ForEach-Object
select Select-Object
sort Sort-Object
ft Format-Table
fl Format-List

Quick Reference Card

HELP          Get-Help <cmd> -Examples
FIND CMD      Get-Command *keyword*
FIND PROPERTY Get-Process | Get-Member
FILTER        ... | Where-Object { $_.Property -eq "Value" }
SELECT COLS   ... | Select-Object Name, Id
SORT          ... | Sort-Object Property -Descending
TOP N         ... | Select-Object -First 10
LOOP ITEMS    ... | ForEach-Object { Write-Host $_ }
EXPORT CSV    ... | Export-Csv file.csv -NoTypeInformation
TO FILE       ... | Out-File file.txt
PREVIEW       <destructive command> -WhatIf

Last updated: 2026 | PowerShell 5.1 / 7.x compatible