Selected topic

Conditional Statements

Flow Control

Prefer practical output? Use related tools below while reading.

Conditional Statements

In PowerShell, conditional statements are used to execute different blocks of code based on certain conditions. These statements help control the flow of your script.

### 1. If Statement

The if statement is used to check if a condition is true or false. If the condition is true, the code within the if block will be executed.

powershell
# Example: Check if a file exists
$file = "C:\temp\example.txt"
if (Test-Path $file) {
    Write-Host "$file exists"
} else {
    Write-Host "$file does not exist"
}

### 2. If-Else Statement

The if-else statement is similar to the if statement, but it also provides an alternative code block to execute if the condition is false.

powershell
# Example: Check if a file exists and delete it if true
$file = "C:\temp\example.txt"
if (Test-Path $file) {
    Remove-Item $file
    Write-Host "$file deleted successfully"
} else {
    Write-Host "$file does not exist"
}

### 3. Switch Statement

The switch statement is used to compare a value against multiple conditions and execute the corresponding code block.

powershell
# Example: Determine the day of the week based on a number
$day = 2
switch ($day) {
    {$_ -eq 1} { Write-Host "Monday" }
    {$_ -eq 2} { Write-Host "Tuesday" }
    {$_ -eq 3} { Write-Host "Wednesday" }
    {$_ -eq 4} { Write-Host "Thursday" }
    {$_ -eq 5} { Write-Host "Friday" }
    {$_ -eq 6} { Write-Host "Saturday" }
    Default { Write-Host "Unknown day" }
}

### 4. Case Statement

The case statement is used to compare a value against multiple conditions and execute the corresponding code block.

powershell
# Example: Determine the month based on a number
$month = 5
switch ($month) {
    {$_ -eq 1} { Write-Host "January" }
    {$_ -eq 2} { Write-Host "February" }
    {$_ -eq 3} { Write-Host "March" }
    {$_ -eq 4} { Write-Host "April" }
    {$_ -eq 5} { Write-Host "May" }
    {$_ -eq 6} { Write-Host "June" }
    Default { Write-Host "Unknown month" }
}

These are the basic conditional statements in PowerShell. They help control the flow of your script and make it more dynamic and efficient.