PowerShell Switch Case with Regex

Recently, I was working on some examples of the PowerShell switch case, and I learned how to use Regex in the Switch case in PowerShell. Let me explain to you with a few examples.

Before discussing using the regex with the PowerShell Switch the statement, let me show you a simple example of the switch statement.

PowerShell Switch Statement

The Switch statement in PowerShell is similar to the switch or case statements found in other programming languages. It evaluates an expression and executes the corresponding block of code based on the value of that expression. Here’s a basic example:

$fruit = "apple"

Switch ($fruit) {
    "apple" { Write-Output "This is an apple." }
    "banana" { Write-Output "This is a banana." }
    "orange" { Write-Output "This is an orange." }
    default { Write-Output "Unknown fruit." }
}

In this example, the Switch statement checks the value of the $fruit variable and executes the corresponding block of code. If $fruit is “apple”, it prints “This is an apple.” If it’s “banana”, it prints “This is a banana.”, and so on. If none of the cases match, the default block is executed.

Now, let me show you how to work with Regex in a PowerShell switch statement.

Regex in PowerShell Switch Statement

Regular expressions are sequences of characters that define a search pattern. In PowerShell, you can use regex with the -match operator or within a Switch statement using the -regex parameter.

To use regex in a Switch statement, you need to specify the -regex parameter. This tells PowerShell to interpret the case values as regular expressions. Here’s an example:

$text = "San Francisco, new york, LOS ANGELES, Dallas, miami"

Switch -Regex -CaseSensitive ($text) {
    "^San Francisco" { Write-Output "The text starts with 'San Francisco'." }
    "new york" { Write-Output "The text contains the city 'new york'." }
    "LOS ANGELES" { Write-Output "The text contains the city 'LOS ANGELES'." }
    "miami$" { Write-Output "The text ends with 'miami'." }
    default { Write-Output "No match found." }
}

In this example, the Switch statement uses regex to match patterns in the $text variable.

After I executed the above PowerShell script, you can see the output in the screenshot below:

powershell switch case regex

Read PowerShell ForEach Loop

Case-Insensitive Match with PowerShell Switch and Regex

By default, the PowerShell Switch statement is case-insensitive when using regex. This means that it will match patterns regardless of the case of the characters in the input string. However, you can explicitly specify case sensitivity if needed. Let’s explore an example of case-insensitive matching using the Switch statement with regex.

Example: Case-Insensitive Match With Regex

Suppose you have a PowerShell list of strings that represent different types of fruit, and you want to categorize them regardless of the case (uppercase or lowercase). Here’s how you can do it with the below PowerShell script.

$fruits = @("Apple", "banana", "CHERRY", "mango", "Pineapple")

foreach ($fruit in $fruits) {
    Switch -Regex ($fruit) {
        "apple" { Write-Output "Found an apple." }
        "banana" { Write-Output "Found a banana." }
        "cherry" { Write-Output "Found a cherry." }
        "mango" { Write-Output "Found a mango." }
        "pineapple" { Write-Output "Found a pineapple." }
        default { Write-Output "Unknown fruit: $fruit" }
    }
}

The Switch statement uses regex patterns to match the fruit names in this example. Because the Switch By default, the statement is case-insensitive; it will match “Apple,” “banana,” “CHERRY,” “mango,” and “Pineapple” correctly, regardless of their case.

You can see the output in the following screenshot after I executed the above PowerShell script.

powershell switch regex case insensitive

Check out PowerShell Switch String Contains

Example: Case Sensitive Match With Regex

If you need to enforce case sensitivity, use the -casesensitive parameter in the PowerShell Switch statement. Here’s how you can modify the previous example to be case-sensitive:

foreach ($fruit in $fruits) {
    Switch -Regex -CaseSensitive ($fruit) {
        "apple" { Write-Output "Found an apple." }
        "banana" { Write-Output "Found a banana." }
        "cherry" { Write-Output "Found a cherry." }
        "mango" { Write-Output "Found a mango." }
        "pineapple" { Write-Output "Found a pineapple." }
        default { Write-Output "Unknown fruit: $fruit" }
    }
}

In this modified example, the Switch statement will only match the fruit names if the case exactly matches the patterns specified (e.g., “apple” will not match “Apple”).

Read While Loop in PowerShell

PowerShell Switch Case with Regex Examples

Let me show you a few examples of the PowerShell Switch case with Regex.

Example-1: Match Digits

To match digits in a string, you can use the \d pattern in a Switch statement with Regex. Here is an example.

$text = "Order number 12345 has been shipped."

Switch -Regex ($text) {
    "\d+" { Write-Output "The text contains digits." }
    default { Write-Output "No digits found." }
}

The \d+ pattern matches one or more digits in the text.

You can see the output in the following screenshot.

powershell switch case regex example

Example-2: Match Words

To match specific words in a string, you can use word boundaries \b in a Switch statement with Regex. Here is the complete PowerShell script.

$text = "PowerShell is a powerful scripting language."

Switch -Regex ($text) {
    "\bPowerShell\b" { Write-Output "The text contains the word 'PowerShell'." }
    "\blanguage\b" { Write-Output "The text contains the word 'language'." }
    default { Write-Output "No matching words found." }
}

Example-3: Match Email Addresses

To match email addresses, you can use the below regex pattern in a switch case in PowerShell.

$text = "Contact us at support@example.com for more information."

Switch -Regex ($text) {
    "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" { Write-Output "The text contains an email address." }
    default { Write-Output "No email address found." }
}

This pattern matches most common email address formats.

After I executed the above PowerShell script, you can see the output in the below screenshot.

powershell switch regex case sensitive

Example-4: Combine Multiple Patterns

This is another example; I will show you how to combine multiple patterns in a Switch statement in PowerShell.

You can combine multiple regex patterns in a single Switch statement to handle more complex scenarios. For example, let’s say you want to match different types of log messages in a text, using the below PowerShell script.

$log = "ERROR: Disk space is low. WARNING: CPU usage is high. INFO: System rebooted."

Switch -Regex ($log) {
    "ERROR:.*" { Write-Output "An error occurred." }
    "WARNING:.*" { Write-Output "A warning was issued." }
    "INFO:.*" { Write-Output "Informational message." }
    default { Write-Output "No log messages found." }
}

In this example, the Switch statement matches different log message types (ERROR, WARNING, INFO) and executes the corresponding code block.

Example-5: Parse Log Files

Let me show you another example of how to parse a log file using the regex in a switch statement.

Here is a log file with different types of messages, and you want to categorize them using the PowerShell script below.

$logMessages = @(
    "ERROR: Disk space is low.",
    "WARNING: CPU usage is high.",
    "INFO: System rebooted.",
    "ERROR: Network connection lost."
)

foreach ($message in $logMessages) {
    Switch -Regex ($message) {
        "ERROR:.*" { Write-Output "Error: $message" }
        "WARNING:.*" { Write-Output "Warning: $message" }
        "INFO:.*" { Write-Output "Info: $message" }
        default { Write-Output "Unknown message type: $message" }
    }
}

This script iterates through each log message and categorizes it based on the type of message (ERROR, WARNING, INFO) using regex patterns in the Switch statement.

Look at the screenshot below for the output.

PowerShell Switch Case with Regex

Example-6: Validate User Input

Suppose you want to validate user input for different types of data, such as email addresses, phone numbers, and postal codes. Here’s how you can do it using regex in a Switch statement:

function Validate-UserInput {
    param (
        [string]$input
    )

    Switch -Regex ($input) {
        "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$" { Write-Output "Valid email address." }
        "^\d{10}$" { Write-Output "Valid phone number." }
        "^\d{5}(-\d{4})?$" { Write-Output "Valid postal code." }
        default { Write-Output "Invalid input." }
    }
}

# Example usage
Validate-UserInput "john.doe@example.com"
Validate-UserInput "1234567890"
Validate-UserInput "12345-6789"
Validate-UserInput "invalid-input"

In this example, the Validate-UserInput() function takes a user input string. It uses a Switch statement with regex patterns to validate whether the input is a valid email address, phone number, or postal code. If the input doesn’t match any of the patterns, it prints “Invalid input.”

Example-7: Extract Data from Text

You can also use regex with the Switch statement to extract specific data from a text string. For example, let’s extract dates from a text using Regex with a Switch statement.

$text = "The project started on 2024-01-15 and ended on 2024-07-10."

Switch -Regex ($text) {
    "\b\d{4}-\d{2}-\d{2}\b" { Write-Output "Date found: $matches[0]" }
    default { Write-Output "No dates found." }
}

In this example, the regex pattern \b\d{4}-\d{2}-\d{2}\b matches dates in the format YYYY-MM-DD. The Switch statement extracts and prints any dates found in the text.

I hope now you know how to use Regex with PowerShell Switch. We discuss a lot of examples.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.