PowerShell Switch Statement

The ultimate tool for complex conditional logic

Why Use Switch?

Unlike a series of if-elseif-else statements, the Switch statement in PowerShell is designed for handling multiple conditions efficiently. It's more readable and often faster, especially when comparing a single variable against many possible values.

Basic Syntax

$value = 10 Switch ($value) { 10 { Write-Host "Exact Match!" } 20 { Write-Host "It is 20" } Default { Write-Host "Something else" } }

Key Features

1. Wildcard Matching

Use the -Wildcard parameter to support asterisks *.

$text = "Error: Server Down" Switch -Wildcard ($text) { "Error*" { Write-Host "Found an error!" } "Warning*" { Write-Host "Just a warning." } }

2. Regex Matching

Use the -Regex parameter for powerful pattern matching.

$email = "user@example.com" Switch -Regex ($email) { "^admin@" { Write-Host "Administrator" } "@example\.com$" { Write-Host "Company Email" } }

3. Processing Arrays

If you pass an array to Switch, it iterates through every item automatically.

$nums = 1, 2, 3, 4, 5 Switch ($nums) { { $_ % 2 -eq 0 } { Write-Host "$_ is Even" } Default { Write-Host "$_ is Odd" } }

Advanced Tips

Continue vs Break: By default, PowerShell Switch continues checking other conditions even after finding a match. Use Break to stop after the first match if desired.

Related Topics