0
0
PowerShellscripting~5 mins

Switch with wildcard and regex in PowerShell

Choose your learning style9 modes available
Introduction

The switch statement helps you check a value against many options easily. Using wildcards and regex lets you match patterns, not just exact words.

You want to run different code based on parts of a word or pattern.
You need to check if a filename matches certain patterns.
You want to handle user input that can vary but follows a pattern.
You want to simplify many <code>if</code> checks into one <code>switch</code>.
You want to find text that fits a pattern inside a list.
Syntax
PowerShell
switch -Wildcard ($value) {
  'pattern1' { # code }
  'pattern2' { # code }
}

switch -Regex ($value) {
  'regex1' { # code }
  'regex2' { # code }
}

-Wildcard lets you use * and ? to match parts of strings.

-Regex lets you use regular expressions for advanced pattern matching.

Examples
This checks if $word starts with 'cat', ends with 'dog', or contains 'bird'.
PowerShell
switch -Wildcard ($word) {
  'cat*' { "Starts with cat" }
  '*dog' { "Ends with dog" }
  '*bird*' { "Contains bird" }
}
This uses regex to do the same checks as above but with more power.
PowerShell
switch -Regex ($word) {
  '^cat' { "Starts with cat" }
  'dog$' { "Ends with dog" }
  'bird' { "Contains bird" }
}
Sample Program

This script checks the string 'catalog' with both wildcard and regex switches. The switch executes only the first matching case for each, printing the corresponding message.

PowerShell
$value = 'catalog'
switch -Wildcard ($value) {
  'cat*' { Write-Output "Matches wildcard: starts with 'cat'" }
  '*log' { Write-Output "Matches wildcard: ends with 'log'" }
  '*dog*' { Write-Output "Matches wildcard: contains 'dog'" }
  default { Write-Output "No wildcard match" }
}
switch -Regex ($value) {
  '^cat' { Write-Output "Matches regex: starts with 'cat'" }
  'log$' { Write-Output "Matches regex: ends with 'log'" }
  'dog' { Write-Output "Matches regex: contains 'dog'" }
  default { Write-Output "No regex match" }
}
OutputSuccess
Important Notes

Use default to catch values that don't match any pattern.

Wildcards are simpler but less powerful than regex.

Regex patterns can be tricky; test them carefully.

Summary

switch with -Wildcard matches simple patterns with * and ?.

switch with -Regex matches complex patterns using regular expressions.

Use these to write cleaner, easier-to-read code when checking many patterns.