【问题标题】:Powershell Switch StatementPowershell 开关语句
【发布时间】:2011-11-04 20:56:51
【问题描述】:

我正在尝试在 Powershell 中编写如下所示的 Switch 语句。

$Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
Switch ($Prompt)
     {
       Y {Get-ChildItem c:\test}
       N {Write-Host "User canceled the request"}
       Default {$Prompt = read-host "Would you like to remove C:\SIN_Store?"}
     }

我想要做的是,如果用户输入了 Y 或 N 以外的任何内容,脚本应该一直提示,直到他们输入其中任何一个。现在发生的情况是,当用户输入 Y 或 N 以外的任何内容时,他们会再次收到提示。但是当他们第二次输入任何字母时,脚本就会退出。它不再要求用户输入。是否可以使用 Switch 完成此操作?谢谢。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我不明白您在代码的默认值中尝试做什么,但根据您的问题,您想将其置于循环中:

    do{
    
    $Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
    Switch ($Prompt)
     {
       Y {Get-ChildItem c:\test}
       N {Write-Host "User canceled the request"}
       Default {continue}
     }
    
    } while($prompt -notmatch "[YN]")
    

    Powershell 的做法:

    $caption="Should I display the file contents c:\test for you?"
    $message="Choices:"
    $choices = @("&Yes","&No")
    
    $choicedesc = New-Object System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription] 
    $choices | foreach  { $choicedesc.Add((New-Object "System.Management.Automation.Host.ChoiceDescription" -ArgumentList $_))} 
    
    
    $prompt = $Host.ui.PromptForChoice($caption, $message, $choicedesc, 0)
    
    Switch ($prompt)
         {
           0 {Get-ChildItem c:\test}
           1 {Write-Host "User canceled the request"}
         }
    

    【讨论】:

      【解决方案2】:

      您不会在任何地方通过管道输入该输入。您可以使用递归函数来做到这一点:

      Function GetInput
      {
      $Prompt = Read-host "Should I display the file contents c:\test for you? (Y | N)" 
      Switch ($Prompt)
           {
             Y {Get-ChildItem c:\test}
             N {Write-Host "User canceled the request"}
             Default {GetInput}
           }
      }
      

      【讨论】:

      • 也谢谢你。很高兴看到它以不同的方式完成。再次感谢您。
      猜你喜欢
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多