# 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="/files/wq8Z7fFsmDki5TkIMIq0" 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="/files/nDyerrpnq8ncb3LMfcTX" 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="/files/lFcBgu8fgkxvRDrYAV3Q" 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="/files/ZPN9m1tVIIrSA8umZKlj" 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="/files/JteEh5eFJJCGHnh4V9lu" 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="/files/4n0Ive4gxqaG3imlX469" 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="/files/rPg7t8sLPjNUw71HweOO" 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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mohab-yehia.gitbook.io/sec505/welcome-to-securing-windows-with-powershell-a-deep-dive-into-sec505/sec-505.1/flow-control-all-in-one.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
