5

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 }
}

2 Answers 2

9

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}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thought it might be a dumb syntax mistake on my part. That change did the trick. Thanks very much Mark.
3

the correct use of the switch statement is:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.