Page cover

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

Example with Scheduled Task


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

Example with Web Server Monitoring


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

Example with Pipeline


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

Example with Complex Logic


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

Example with Wildcards

Example with Regular Expressions

Example with Arrays

Example with Text Files

Last updated