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
}
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.