How to Use If Else in PowerShell: Simple Syntax and Examples
In PowerShell, use
if to run code when a condition is true, and else to run code when it is false. The basic form is if (condition) { commands } else { commands }. This lets you control the flow based on conditions.Syntax
The if statement checks a condition inside parentheses. If the condition is true, it runs the code inside the first curly braces. The optional else runs code inside its braces if the condition is false.
- if (condition): Tests the condition.
- { }: Contains commands to run if true.
- else { }: Contains commands to run if false (optional).
powershell
if (<condition>) { # commands if true } else { # commands if false }
Example
This example checks if a number is greater than 10 and prints a message accordingly.
powershell
$number = 15 if ($number -gt 10) { Write-Output "Number is greater than 10" } else { Write-Output "Number is 10 or less" }
Output
Number is greater than 10
Common Pitfalls
Common mistakes include missing parentheses around the condition or forgetting curly braces. Also, using single equals = instead of comparison operators like -eq causes errors.
PowerShell uses operators like -eq (equals), -ne (not equals), -gt (greater than), -lt (less than).
powershell
Wrong: if ($number = 10) { Write-Output "Equal to 10" } Right: if ($number -eq 10) { Write-Output "Equal to 10" }
Quick Reference
| Operator | Meaning |
|---|---|
| -eq | Equals |
| -ne | Not equals |
| -gt | Greater than |
| -lt | Less than |
| -ge | Greater or equal |
| -le | Less or equal |
Key Takeaways
Use parentheses around the condition in
if statements.Curly braces
{ } enclose the code blocks for true and false cases.Use PowerShell comparison operators like
-eq, -gt, not =.The
else block is optional and runs when the if condition is false.Always test your conditions to avoid syntax errors.