Page cover image

Flow Control (All in one)

Flow control statements allow you to control the execution of your scripts based on conditions, loops, and switches. PowerShell provides several flow control constructs, including If-ElseIf-Else, While, Do-While, ForEach, For, and Switch. Each of these constructs serves a specific purpose and can be used to make your scripts more dynamic and efficient.


1. If-ElseIf-Else

Definition

The If-ElseIf-Else statement is used to execute different blocks of code based on one or more conditions. It evaluates a condition, and if the condition is $true, the corresponding block of code is executed. If the condition is $false, it moves to the next condition (ElseIf) or executes the Else block if no conditions are met.

Example

$string = "SANS has GIAC training for the GCWN cert."
If ($string -like "SANS*") {
    "It's true that it starts with SANS."
} ElseIf ($string -match "[FGH]IAC") {
    "It matches the regular expression pattern."
} ElseIf ($string -eq "GCWN") {
    "It matches the string exactly."
} Else {
    "None of the above tests resolved to $true."
}

2. While Loop

Definition

The While loop repeatedly executes a block of code as long as a specified condition is $true. If the condition is $false initially, the loop will not execute at all.

Example

$rabbits = 2
While ($rabbits -lt 10000) {
    "We now have $rabbits!"
    $rabbits = $rabbits * 2
}

Example with Scheduled Task

Start-ScheduledTask -TaskPath "\SEC505\" -TaskName "SetUID"
$Task = Get-ScheduledTask -TaskName "SetUID"
While ($Task.State -eq "Running") {
    "Task Still Running: " + (Get-Date).DateTime
    Start-Sleep -Seconds 10
    $Task = Get-ScheduledTask -TaskName "SetUID"
}
"Task Completed: " + (Get-Date).DateTime

3. Do-While Loop

Definition

The Do-While loop is similar to the While loop, but it guarantees that the block of code will execute at least once, even if the condition is $false initially.

Example

$rabbits = 2
Do {
    "We now have $rabbits!"
    $rabbits *= 2
} While ($rabbits -lt 10000)

Example with Web Server Monitoring

Do {
    $Result = Test-NetConnection -ComputerName 10.1.1.1 -Port 80
    Start-Sleep -Seconds 60
} While ($Result.TcpTestSucceeded)
"Web Server Test Failure: " + (Get-Date).DateTime

4. ForEach Loop

Definition

The ForEach loop is used to iterate over a collection or array. It processes each item in the collection one by one.

Example

$Services = Get-Service
ForEach ($Svc in $Services) {
    $Svc.Name + ": " + $Svc.Status
}

Example with Pipeline

Get-Service | ForEach-Object { $_.Name + ": " + $_.Status }

5. For Loop

Definition

The For loop is used to execute a block of code a specific number of times. It consists of three parts: initialization, condition, and increment.

Example

For ($i = 0; $i -le 20; $i++) {
    "Now at $i"
}

Example with Complex Logic

For ($i = 0, $j = 0; $i -lt 10; $i++, $j += 2) {
    "i = $i, j = $j"
}

6. Switch Statement

Definition

The Switch statement is used to compare a value against multiple conditions. It can handle exact matches, wildcards, and regular expressions.

Example

$x = 58
Switch ($x) {
    {$_ -lt 20} { "Really Small" }
    {$_ -gt 50} { "Pretty Big" }
    58 { "It's 58" }
    Default { "What was that?" }
}

Example with Wildcards

Switch -Wildcard ("c:\data5\archive.zip") {
    '?:\data?\*' { "In some data folder." }
    '*.zip' { "File is a ZIP." }
}

Example with Regular Expressions

Switch -Regex ("c:\data5\archive.zip") {
    '\\data[0-9]+\\' { "In some data folder." }
    '\.ZIP$|\.BKF$|\.TAR$' { "File is a ZIP or BKF or TAR." }
}

Example with Arrays

$stopped = $running = $paused = 0
Switch (Get-Service) {
    {$_.Status -like "Running"} { $running++ }
    {$_.Status -like "Stopped"} { $stopped++ }
    {$_.Status -like "Paused"} { $paused++ }
}
"Services Running = $running"
"Services Stopped = $stopped"
"Services Paused = $paused"

Example with Text Files

$HashTable = @{}
Switch -RegEx -File .\pfirewall.log {
    "DROP\sTCP.+RECEIVE" {
        $SrcIP = ($_ -Split " ")[4]
        If ($HashTable.ContainsKey($SrcIP)) {
            $HashTable.Item($SrcIP) = $HashTable.Item($SrcIP) + 1
        } Else {
            $HashTable.Add($SrcIP, 1)
        }
    }
}
$HashTable.GetEnumerator() | Sort-Object Value -Descending

Last updated