0
0
PowerShellscripting~5 mins

Why control flow directs execution in PowerShell

Choose your learning style9 modes available
Introduction
Control flow tells the script what to do next. It helps decide which parts run and when, so your script works step by step.
When you want to repeat a task multiple times, like checking files every minute.
When you need to choose between two or more actions, like asking if a user wants to continue.
When you want to stop running a script if something goes wrong.
When you want to run different code based on a condition, like if a number is big or small.
Syntax
PowerShell
if (<condition>) {
    # code to run if condition is true
} elseif (<another condition>) {
    # code if second condition is true
} else {
    # code if no conditions are true
}

while (<condition>) {
    # code to repeat while condition is true
}

for (<init>; <condition>; <change>) {
    # code to repeat with a counter
}
Conditions are expressions that are either true or false.
Curly braces { } group the code that runs together.
Examples
Checks if age is 18 or more, then prints a message.
PowerShell
if ($age -ge 18) {
    Write-Output "You can vote."
} else {
    Write-Output "You are too young to vote."
}
Repeats printing count while it is less than 5.
PowerShell
while ($count -lt 5) {
    Write-Output "Count is $count"
    $count++
}
Runs the loop 3 times, printing the number each time.
PowerShell
for ($i = 1; $i -le 3; $i++) {
    Write-Output "Number $i"
}
Sample Program
This script checks the value of $number and prints a message based on its value.
PowerShell
$number = 7
if ($number -gt 10) {
    Write-Output "Number is greater than 10"
} elseif ($number -eq 7) {
    Write-Output "Number is exactly 7"
} else {
    Write-Output "Number is 10 or less and not 7"
}
OutputSuccess
Important Notes
Use control flow to make your scripts smart and flexible.
Always test your conditions to avoid unexpected results.
Indent your code inside braces to keep it readable.
Summary
Control flow guides which parts of a script run and when.
Use if, elseif, else to choose between actions.
Use loops like while and for to repeat actions.