问题
I am having trouble getting a simple switch statement to work in a Powershell script I'm using. Had previously been using nested ifs 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.
Thanks in advance for any thoughts/suggestions.
Switch ($myString)
{
($_ -match 'match1') {somecodeblock}
($_ -match 'match2') {somecodeblock}
($_ -match 'match3') {somecodeblock}
($_ -match 'match3') {somecodeblock}
($_ -match 'match4') {somecodeblock}
($_ -match 'match4') {somecodeblock}
}
回答1:
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}
}
回答2:
the correct use of the switch statement is:
Switch -regex ($myString)
{
'match1' {somecodeblock}
'match2' {somecodeblock}
}
来源:https://stackoverflow.com/questions/43096777/powershell-switch-statement-string-match-not-working