Programing

switch 문의 여러 값에 대한 PowerShell 구문은 무엇입니까?

crosscheck 2020. 11. 10. 07:51
반응형

switch 문의 여러 값에 대한 PowerShell 구문은 무엇입니까?


기본적으로 이렇게하고 싶습니다.

switch($someString.ToLower())
{
    "y", "yes" { "You entered Yes." }
    default { "You entered No." }
}

switch($someString.ToLower()) 
{ 
    {($_ -eq "y") -or ($_ -eq "yes")} { "You entered Yes." } 
    default { "You entered No." } 
}

나는 이것이 작동하고 더 읽기 쉽다는 것을 발견했습니다.

switch($someString)
{
    { @("y", "yes") -contains $_ } { "You entered Yes." }
    default { "You entered No." }
}

"-contains"연산자는 대소 문자를 구분하지 않는 검색을 수행하므로 "ToLower ()"를 사용할 필요가 없습니다. 대소 문자를 구분하려면 대신 "-ccontains"를 사용할 수 있습니다.


값에 와일드 카드를 사용할 수 있어야합니다.

switch -wildcard ($someString.ToLower())
{
    "y*" { "You entered Yes." }
    default { "You entered No." }
}

정규식도 허용됩니다.

switch -regex ($someString.ToLower())
{
    "y(es)?" { "You entered Yes." }
    default { "You entered No." }
}

PowerShell 스위치 설명서 : Switch 문 사용


switch($someString.ToLower())
{
    "yes"   { $_ = "y" }
    "y"     { "You entered Yes." }
    default { "You entered No." }
}

대상 케이스가 $ _ 변수가 각각 재 할당 된 케이스 아래 / 뒤에 있는 한이 방식으로 케이스를 임의로 분기, 캐스케이드 및 병합 할 수 있습니다 .


nb이 동작만큼 귀엽지 만, PowerShell 인터프리터가 기대하거나 예상하는 것만 큼 효율적으로 스위치 / 케이스를 구현하지 않고 있음을 드러내는 것 같습니다. 첫째, ISE 디버거를 사용하면 최적화 된 조회, 해싱 또는 이진 분기 대신 여러 if-else 문처럼 각 사례가 차례로 테스트된다는 것을 알 수 있습니다. (그렇다면 가장 일반적인 사례를 먼저 배치하는 것이 좋습니다.) 또한이 답변에서 볼 수 있듯이 PowerShell은 사례를 충족 한 후 계속 테스트합니다. 그리고 잔인하게도 .NET CIL에서 사용할 수있는 최적화 된 특수 '스위치'opcode도 있습니다.이 동작으로 인해 PowerShell은 활용할 수 없습니다.


y | ye | yes 입력을 지원하고 대소 문자를 구분하지 않습니다.

switch -regex ($someString.ToLower()) {
        "^y(es?)?$" {
            "You entered Yes." 
        }
        default { "You entered No." }
}

정규식의 대체 연산자 "|"(파이프)를 사용하여 원래 요청을 충족하도록 derekerdmann의 게시물을 약간 수정했습니다.

It's also slightly easier for regex newbies to understand and read.

Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").

Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.

switch -regex ($someString) #many have noted ToLower() here is redundant
{
        #processing user input
    "^(y|yes|indubitably)$" { "You entered Yes." }

        # not processing user input
    "y|yes|indubitably" { "Yes was the selected string" } 
    default { "You entered No." } 
}

After searching a solution for the same problem like you, I've found this small topic here. In advance I got a much smoother solution for this switch, case statement

switch($someString) #switch is caseINsensitive, so you don't need to lower
{
    { 'y' -or 'yes' } { "You entered Yes." }
    default { "You entered No." }
}

참고URL : https://stackoverflow.com/questions/3493731/whats-the-powershell-syntax-for-multiple-values-in-a-switch-statement

반응형