PowerShell-Technique: Switching

Created March 30, 2023

Enhance Your PowerShell Scripting with Switch Statements

Have you ever found yourself writing a lot of if/elseif/else statements in your PowerShell script? You may have heard of the switch statement as an alternative, but do you know all of its capabilities?

Let's start with an example that uses if/elseif/else statements:

$Age = 16
$Drink = $Null
if($Age -lt 16){
    $Drink = "Soft Drink"
}elseif($Age -lt 18){
    $Drink = "SoftDrink","Wine","Beer"
}else{
    $Drink = "SoftDrink","Wine","Beer", "Booze"
}

While this code works and achieves our goal, it can quickly become difficult to read and maintain as the number of conditions increases. Fortunately, the switch statement can simplify our code and make it easier to read:

$Age = 16
$Drink = $Null

switch ($Age) {
    { $_ -lt 16 } { $Drink = "Soft Drink"; break }
    { $_ -lt 18 } { $Drink = "SoftDrink","Wine","Beer"; break }
    default { $Drink = "SoftDrink","Wine","Beer", "Booze" }
}

This code is more readable, structured, and aesthetically pleasing. Additionally, the switch statement allows us to use regular expressions to match patterns, as shown in the following example:

$logFile = "C:\Logs\access.log"
$ipAddresses = @()
$urls = @()
$emailAddresses = @()

switch -regex (Get-Content $logFile) {
    "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" { $ipAddresses += $matches[0] }
    "http(s)?://[^\s]*"                     { $urls += $matches[0] }
    "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b" { $emailAddresses += $matches[0] }
    default                                 { continue }
}

In this example, we use the -regex parameter to match IP addresses, URLs, and email addresses in a log file and store them in separate arrays. The switch statement makes it easy to execute different code for each pattern.

Finally, we can use wildcards as conditions in a switch statement. The following example demonstrates how to use wildcards to check for different file versions:

$fileName = "example_file_v1.2.csv"

switch -wildcard ($fileName) {
    "*_v1.*" { Write-Host "This is version 1 of the file." }
    "*_v2.*" { Write-Host "This is version 2 of the file." }
    "*_v3.*" { Write-Host "This is version 3 of the file." }
    default  { Write-Host "This is an unknown version of the file." }
}

In this example, we use the -wildcard parameter to check if a file name contains a specific keyword. The switch statement makes it easy to match patterns against a string and execute different code based on the matching pattern.

By using switch statements in PowerShell, you can simplify your code, improve its readability, and take advantage of its powerful features, such as regular expressions and wildcards.

Thats all for now.

If you have any thoughts or feedback on this topic, feel free to share them with me on Twitter at Christian Ritter. Best regards,

Christian.