PowerShell: How to Use Regex in Switch Statement


You can use the following syntax in PowerShell to use regex with a switch statement:

Get-Content $my_file | ForEach-Object {
  switch($_) {
    {$_ -match "Manager" } { "Manager Position" }
    default { "Not a Manager Position" }
  }
}

This particular example does the following:

  • Use Get-Content to get the content of the file specified at the path in the $my_file variable.
  • Use ForEach-Object to loop through each line in the file.
  • Use switch with the -match operator to check if each line contains “Manager” in the string and output one of two strings as a result.

By using the -match operator, we are able to check if each line in the file contains a specific pattern anywhere in the string.

The following example shows how to use this syntax in practice.

Example: How to Use Regex in Switch Statement in PowerShell

Suppose we have a text file located at the following location:

  • c:\users\bobbi\company_info.txt

We can use the Get-Content cmdlet to view the contents of this file:

The file contains seven employee ID numbers for various individuals who work at some company.

Suppose that we would like to check if each employee ID number contains the string “Manager” anywhere in the ID and output one of the following strings as a result:

  • “Manager Position”
  • “Not a Manager Position”

We can use the following syntax to do so:

$my_file = "c:\users\bobbi\company_info.txt"

Get-Content $my_file | ForEach-Object {
  switch($_) {
    {$_ -match "Manager" } { "Manager Position" }
    default { "Not a Manager Position" }
  }
}

The following screenshot shows how to use this syntax in practice:

PowerShell use regex with switch statement

The switch statement returns “Manager Position” for each line in the file that contains “Manager” in the Employee ID string.

Otherwise, the switch statement returns “Not a Manager Position” if the pattern “Manager” is not detected in the Employee ID string.

Note: You can find the complete documentation for the switch statement in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Multiple Values in Switch Statement
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Special Characters in String

Leave a Reply