Skip to content

PowerShell Scripting Cheat Sheet

Quick reference for common PowerShell scripting patterns.

Terminal window
$variable = "value" # Create/assign variable
$number = 42
$result = Get-Date
[int]$age = 25 # Declare type explicitly
$var = $null # Empty variable
Terminal window
$greeting = "Hello, " + $name # Concatenation
$message = "Hello, $name" # String interpolation ($ works inside "")
$text = 'No $variables here' # Single quotes are literal
$path = "C:\folder\file.txt" # Escape backslash: C:\\
$fullname = "$first$last" # Multiple variables
[string]$text = "Convert to string"
Terminal window
$arr = @(1, 2, 3, 4, 5) # Create array
$arr[0] # Access first element (0-based)
$arr[-1] # Last element
$arr.Length # Array size
$arr += 6 # Add element
Terminal window
Write-Host "Display text" # Output to console
Write-Host "Red text" -ForegroundColor Red
Write-Host -NoNewline "No newline" # Same line
$input = Read-Host -Prompt "Enter value" # Get user input
$input = Read-Host "Enter value" # Same (prompt optional)
Terminal window
Test-Path -LiteralPath $filepath # File/folder exists?
Set-Content -Path $file -Value $data # Create/overwrite file
Add-Content -Path $file -Value $data # Append to file
Get-Content -Path $file # Read entire file
Remove-Item -Path $file # Delete file
Get-ChildItem -Path "C:\folder" # List directory
Terminal window
If ($condition) {
# Code runs if true
}
If ($x -eq 5) {
# Equal to
} ElseIf ($x -lt 5) {
# Less than
} Else {
# None of above
}
Terminal window
-eq # Equal
-ne # Not equal
-lt # Less than
-le # Less than or equal
-gt # Greater than
-ge # Greater than or equal
-and # AND (both must be true)
-or # OR (at least one true)
-not # NOT (reverse true/false)
-contains # Array contains value
Terminal window
For ($i = 1; $i -le 10; $i++) {
Write-Host $i
}
# Prints 1 through 10
For ($i = 0; $i -lt $arr.Length; $i++) {
Write-Host $arr[$i]
}
# Loop through array by index
Terminal window
While ($count -lt 10) {
Write-Host $count
$count++
}
# Runs while condition is true
Do {
$answer = Read-Host "Enter y or n"
} While (($answer -ne "y") -and ($answer -ne "n"))
# Do-While: runs at least once
Terminal window
ForEach ($item in $array) {
Write-Host $item
}
# Loop through each element
$numbers | ForEach-Object { $_ * 2 }
# Pipeline version (advanced)
Terminal window
# Access via $args
If ($args[0]) { $duration = $args[0] } # First argument
If ($args[1]) { $filename = $args[1] } # Second argument
# Formal parameters (cleaner)
param (
[int]$duration = 60,
[string]$filename = "output.txt"
)
# Usage: .\script.ps1 -duration 120 -filename "results.txt"
Terminal window
function Add-Numbers($a, $b) {
return $a + $b
}
$result = Add-Numbers 5 3
Write-Host $result # Output: 8
function CheckValidity($input) {
If ($input -eq '1' -or $input -eq '2') {
return $true
}
return $false
}
Terminal window
# Single line comment
<# Multi-line comment
Very useful for longer
explanations #>
Terminal window
$value = If ($condition) { "true value" } Else { "false value" }
# Sets $value based on condition
If ($age -ge 18) {
$status = "Adult"
} Else {
$status = "Minor"
}
Terminal window
Switch ($choice) {
'1' { Write-Host "Option 1" }
'2' { Write-Host "Option 2" }
'9' { exit }
default { Write-Host "Invalid choice" }
}
Terminal window
$length = $string.Length # String character count
$count = ($array).Count # Array element count
$lines = @(Get-Content $file).Length # File line count
Terminal window
exit # Exit immediately
exit 0 # Exit with success code
exit 1 # Exit with error code
Terminal window
Get-Date # Current date/time
Get-Date -Format "yyyyMMddHHmmss" # Formatted: 20240115143022
$later = (Get-Date) + (New-TimeSpan -Seconds 60) # Add 60 seconds
Terminal window
clear # Clear console
cls # Same thing
Terminal window
$count++ # Add 1
$count-- # Subtract 1
$count += 5 # Add 5
$count -= 3 # Subtract 3
Terminal window
If (($age -ge 18) -and ($license -eq $true)) {
# Both must be true
}
If (($choice -ne '1') -and ($choice -ne '2') -and ($choice -ne '9')) {
# Repeat until valid input
}
If (($status -eq 'Active') -or ($status -eq 'Pending')) {
# At least one is true
}