Using Switch in PowerShell for Better Comparisons

Posted by:

|

On:

|

A PowerShell Switch is for when you’ve ascended beyond simple if statements and crave more power. The benefit allows for many conditionals in a small code block. This generally will be used with strings or integers but can work on many data types and even files.

PowerShell
switch [-regex | -wildcard | -exact] [-casesensitive] $testExpression
# $testExpression can also be "-file $filename"

    {
    "string" | number | variable | { 
        <value-scriptblock> } {
            <action-scriptblock>
        }
    default { <action-scriptblock> } # optional
    }

Switch Parameters

Without parameters, the command will evaluate using -exact but not -casesensitive and will expect an expression. If the expression is a collection, it will be evaluated in order.

The default clause isn’t needed, but if inserted will serve as else and fire if no other matches. This means you can only have one per.

Notes about parameters:

  • All conditions are case-insensitive unless -caseinsensitive is used.
  • -Wildcard looks for “*$testExpression*”.
  • -Exact looks for $testExpression. Only used on strings.
  • -File will evaluate the contents of a file line-by-line.
  • -Regex is oddly enough case-insensitive but allows for use of the $matches variable.
  • If conflicting parameters are used, only the last one is evaluated.

The Value script block can be any expression. The Action script block is obviously code to execute but can also include flow-control statements like break as well as exit codes that can be passed. Lastly, if break is not used, the expression will compare against all branches and can trigger multiple action blocks.

PowerShell
$url = "https://www.wizardshell.com/powershell-switches" # ( ͡° ͜ʖ ͡°)
$blockedWebsites = @()

$allowedUrls = @(
    "https://www.wizardshell.com", 
    "https://www.microsoft.com"
)


switch -regex ($url) {
    ($allowedUrls -join '|') { # This separates the array with pipes for regex
        Write-Output "This URL is already allowed."
        exit 0  # success
    }
    "https" {
        Write-Output("This is a secure website.")
        break
    }
    "\.edu" {
        Write-Output("This is an school website.")
    }
    "http\/" {
        Write-Output("This is an unsecure website.")
        $blockedWebsites += $url
    }
    default {
        Write-Output("This website is not educational or secure.")
        exit 1 # failure
    }
}

This is a flexible way to manage logic and becomes more powerful if your expression can fit multiple conditions. The example above doesn’t make practical sense, but shows some expressions, including regular expressions, script blocks, and exit codes.

All in all, this helps if there are a lot of moving parts or overlapping expressions. You can have a script block break or exit to avoid running the next line to ensure only certain actions run.

This is a very powerful tool when implemented correctly, but still fun to use regardless.