Jeff
Jeff

Reputation: 75

Powershell Switch Statement String Match Not Working

I am having trouble getting a simple switch statement to work in a Powershell script I'm using. Had previously been using nested if's and wanted to clean up a bit. Code is below.

When I walk it through Powershell ISE in debug and evaluate the tests (e.g. $_ -match 'match1' ) it does evaluate to true as expected based on the value of $mystring. However, it never seems to properly execute the code associated with that value in the Switch block. I'm sure I'm missing something obvious, and appreciate any guidance. Hope my description makes sense. I'm running v5.1.

Switch ($myString)
{
  ($_ -match 'match1') { somecodeblock }
  ($_ -match 'match2') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
}

Upvotes: 4

Views: 15087

Answers (2)

fbehrens
fbehrens

Reputation: 6551

the correct use of the switch statement is:

Switch -regex ($myString)
{
  'match1' {somecodeblock}
  'match2' {somecodeblock}
}

Upvotes: 3

Mark Wragg
Mark Wragg

Reputation: 23385

The correct syntax is to use curly braces around your test when using $_ (you are currently using brackets):

Switch ($myString)
{
   {$_ -match 'match1'} {somecodeblock}
}

When you are not using $_ they can be ommitted from the test entirely, and you could do this if you used the -wildcard parameter:

Switch -wildcard ($myString)
{
   '*match1*' {somecodeblock}
}

Upvotes: 8

Related Questions