Powershell Switch Statement String Match Not Working

南楼画角 提交于 2021-01-29 04:35:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!