# 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."
}
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FnXkAwvKRndPVqkWhq4Yg%2Fimage.png?alt=media&#x26;token=9f0c4a71-3231-494a-a084-a018def165b4" alt=""><figcaption></figcaption></figure>

***

#### **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
}
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FepXA8HMwDrvlrjmQ4Zbx%2Fimage.png?alt=media&#x26;token=963c69e9-68a0-4518-8c87-a58a221de5e1" alt=""><figcaption></figcaption></figure>

**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)
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FHGbj3W0LKn8nhIwnH3JK%2Fimage.png?alt=media&#x26;token=11cf3772-4763-4692-8e46-00b05ecd00d8" alt=""><figcaption></figcaption></figure>

**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 }
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FIRZYadfg6rGfM3Iw0Jss%2Fimage.png?alt=media&#x26;token=b6e5a264-fb47-460c-9afc-b508a13f93f0" alt=""><figcaption></figcaption></figure>

***

#### **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"
}
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2F2UjbG2wGWofY3Dbp3MJh%2Fimage.png?alt=media&#x26;token=c16d402f-12dc-40ce-8a75-969d2da61eb8" alt=""><figcaption></figcaption></figure>

**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?" }
}
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2F265pO6Bm8XyqoyeabTQ0%2Fimage.png?alt=media&#x26;token=97ffccf5-d8a1-4f01-aacf-ba295ae9b4a8" alt=""><figcaption></figcaption></figure>

**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"
```

<figure><img src="https://2325329360-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxV3NRyPsEjkbBdVUnFZk%2Fuploads%2FsKlEl9dSfB45GnmWQ13t%2Fimage.png?alt=media&#x26;token=2ba3f331-708c-4a2f-b97c-4d6492fbb999" alt=""><figcaption></figcaption></figure>

**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
```
