CodeToLive

PowerShell Control Flow

Control flow statements allow you to make decisions and repeat actions in your PowerShell scripts.

Conditional Statements

If-ElseIf-Else

$temperature = 25

if ($temperature -lt 0) {
    "Freezing weather"
}
elseif ($temperature -lt 20) {
    "Cool weather"
}
elseif ($temperature -lt 30) {
    "Pleasant weather"
}
else {
    "Hot weather"
}

Switch Statements

$day = "Wednesday"

switch ($day) {
    "Monday"    { "Start of work week" }
    "Friday"    { "Almost weekend!" }
    {$_ -in "Saturday","Sunday"} { "Weekend!" }
    default     { "Midweek day" }
}

# Advanced switch with expressions
$value = 15
switch ($value) {
    {$_ -lt 10}  { "Single digit" }
    {$_ % 2 -eq 0} { "Even number" }
    default { "Odd number greater than 10" }
}

Looping Constructs

For Loop

# Basic for loop
for ($i = 1; $i -le 5; $i++) {
    "Iteration $i"
}

# Looping through array
$services = "WinRM", "Spooler", "Bits"
for ($i = 0; $i -lt $services.Count; $i++) {
    "Service $($i+1): $($services[$i])"
}

Foreach Loop

# Foreach statement
$processes = Get-Process
foreach ($process in $processes) {
    if ($process.WorkingSet -gt 100MB) {
        "$($process.Name) is using $($process.WorkingSet/1MB) MB"
    }
}

# Foreach method (PowerShell 4.0+)
(Get-Process).ForEach({
    if ($_.WorkingSet -gt 100MB) {
        "$($_.Name) is using $($_.WorkingSet/1MB) MB"
    }
})

While Loop

# While loop
$counter = 1
while ($counter -le 3) {
    "Counter: $counter"
    $counter++
}

# Reading input until condition
$input = ""
while ($input -ne "quit") {
    $input = Read-Host "Enter text (type 'quit' to exit)"
    "You entered: $input"
}

Do-While Loop

# Do-While (executes at least once)
do {
    $number = Get-Random -Minimum 1 -Maximum 10
    "Random number: $number"
} while ($number -ne 5)

Loop Control Statements

# Break statement
foreach ($file in Get-ChildItem) {
    if ($file.Length -gt 1MB) {
        "Found first large file: $($file.Name)"
        break
    }
}

# Continue statement
1..10 | ForEach-Object {
    if ($_ % 2 -eq 0) { continue }
    "Odd number: $_"
}

# Labeled break
:outerLoop for ($i = 1; $i -le 3; $i++) {
    for ($j = 1; $j -le 3; $j++) {
        if ($i * $j -gt 4) { break outerLoop }
        "$i x $j = $($i * $j)"
    }
}

Comparison Operators

Operator Description Example
-eq Equal $a -eq $b
-ne Not equal $a -ne $b
-gt Greater than $a -gt $b
-ge Greater than or equal $a -ge $b
-lt Less than $a -lt $b
-le Less than or equal $a -le $b
-like Wildcard comparison $name -like "A*"
-notlike Wildcard not match $name -notlike "A*"
-match Regular expression match $text -match "^[A-Z]"
-notmatch Regex not match $text -notmatch "^[A-Z]"
-in Contained in collection $day -in @("Sat","Sun")
-notin Not in collection $day -notin @("Sat","Sun")

Logical Operators

# -and operator
if ($age -ge 18 -and $age -le 65) {
    "Working age"
}

# -or operator
if ($day -eq "Saturday" -or $day -eq "Sunday") {
    "Weekend!"
}

# -not operator
if (-not $isAdmin) {
    "Admin privileges required"
}

# Combining operators
if (($age -ge 21 -and $country -eq "US") -or $age -ge 18) {
    "Can drink alcohol"
}

Error Handling

# Try/Catch/Finally
try {
    $result = 10 / $null
}
catch [System.DivideByZeroException] {
    "Cannot divide by zero"
}
catch {
    "Other error occurred: $_"
}
finally {
    "Cleanup code here"
}

# ErrorAction parameter
Get-Content "nonexistent.txt" -ErrorAction SilentlyContinue

# $Error automatic variable
if ($Error.Count -gt 0) {
    "Last error: $($Error[0].Exception.Message)"
}