PowerShell Scripting Cheat Sheet
Quick reference for common PowerShell scripting patterns.
Variables
Section titled “Variables”$variable = "value" # Create/assign variable$number = 42$result = Get-Date[int]$age = 25 # Declare type explicitly$var = $null # Empty variableString Operations
Section titled “String Operations”$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"Arrays
Section titled “Arrays”$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 elementInput/Output
Section titled “Input/Output”Write-Host "Display text" # Output to consoleWrite-Host "Red text" -ForegroundColor RedWrite-Host -NoNewline "No newline" # Same line$input = Read-Host -Prompt "Enter value" # Get user input$input = Read-Host "Enter value" # Same (prompt optional)File Operations
Section titled “File Operations”Test-Path -LiteralPath $filepath # File/folder exists?Set-Content -Path $file -Value $data # Create/overwrite fileAdd-Content -Path $file -Value $data # Append to fileGet-Content -Path $file # Read entire fileRemove-Item -Path $file # Delete fileGet-ChildItem -Path "C:\folder" # List directoryIf/Else Statements
Section titled “If/Else Statements”If ($condition) { # Code runs if true}
If ($x -eq 5) { # Equal to} ElseIf ($x -lt 5) { # Less than} Else { # None of above}Comparison Operators
Section titled “Comparison Operators”-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 valueFor Loop
Section titled “For Loop”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 indexWhile Loop
Section titled “While Loop”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 onceForEach Loop
Section titled “ForEach Loop”ForEach ($item in $array) { Write-Host $item}# Loop through each element
$numbers | ForEach-Object { $_ * 2 }# Pipeline version (advanced)Parameters (Script Arguments)
Section titled “Parameters (Script Arguments)”# Access via $argsIf ($args[0]) { $duration = $args[0] } # First argumentIf ($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"Functions
Section titled “Functions”function Add-Numbers($a, $b) { return $a + $b}
$result = Add-Numbers 5 3Write-Host $result # Output: 8
function CheckValidity($input) { If ($input -eq '1' -or $input -eq '2') { return $true } return $false}Comments
Section titled “Comments”# Single line comment
<# Multi-line comment Very useful for longer explanations #>Conditional Assignment
Section titled “Conditional Assignment”$value = If ($condition) { "true value" } Else { "false value" }
# Sets $value based on conditionIf ($age -ge 18) { $status = "Adult"} Else { $status = "Minor"}Switch Statement
Section titled “Switch Statement”Switch ($choice) { '1' { Write-Host "Option 1" } '2' { Write-Host "Option 2" } '9' { exit } default { Write-Host "Invalid choice" }}Counting/Measuring
Section titled “Counting/Measuring”$length = $string.Length # String character count$count = ($array).Count # Array element count$lines = @(Get-Content $file).Length # File line countExiting Script
Section titled “Exiting Script”exit # Exit immediatelyexit 0 # Exit with success codeexit 1 # Exit with error codeDate/Time
Section titled “Date/Time”Get-Date # Current date/timeGet-Date -Format "yyyyMMddHHmmss" # Formatted: 20240115143022$later = (Get-Date) + (New-TimeSpan -Seconds 60) # Add 60 secondsClear Screen
Section titled “Clear Screen”clear # Clear consolecls # Same thingIncrement/Decrement
Section titled “Increment/Decrement”$count++ # Add 1$count-- # Subtract 1$count += 5 # Add 5$count -= 3 # Subtract 3Multiple Conditions
Section titled “Multiple Conditions”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}