循环直到用户输入三个必需字母之一

时间:2016-01-05 07:01:52

标签: powershell do-while

目前我有这个:

do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} while ($MAB -ne "M","A","B")

但它并不适合我。

我需要它做的是请求用户是否需要广告​​,强制或两者,并根据他们需要他们输入M表示强制性,A表示广告或B表示两者。

目前,如果我输入3个字母中的任何一个,请使用我上面的内容,它只是再次询问。

如果我这样设置:

do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} while ($MAB -ne "M")

它工作正常,虽然这对A或B输入没有帮助。

此外,如果您可以解释我如何抛出错误说"您必须输入A代表广告,B代表两者,或M代表强制性,继续。"如果他们放入M,A或B以外的任何东西。

4 个答案:

答案 0 :(得分:3)

$title = "Deployment choices"
$message = "Do you require a Mandatory and/or Advertised deployment?"

$mandatory = New-Object System.Management.Automation.Host.ChoiceDescription "&Mandatory"
$advertised = New-Object System.Management.Automation.Host.ChoiceDescription "&Advertised"
$both = New-Object System.Management.Automation.Host.ChoiceDescription "&Both"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($mandatory, $advertised, $both)

#do
#{
    $result = $host.ui.PromptForChoice($title, $message, $options, 0) 

    switch ($result)
    {
        0 {"You selected Mandatory."}
        1 {"You selected Advertised."}
        2 {"You selected Both." }
    }
#}
#until ($result -in 0..2)

答案 1 :(得分:1)

我认为这很简洁:

do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} until ($("M","A","B").Contains($MAB))

答案 2 :(得分:0)

好的,所以我发现了 - 我一整天都在寻找这个,很难找到倍数的答案。

它实际上不是do..while,而是do..until

do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} until (($MAB -eq "M") -or ($MAB -eq "A") -or ($MAB -eq "B"))

我希望这可以帮助其他人。

答案 3 :(得分:0)

另一个选项是choice命令:

choice /c mab /m 'Do you require a Mandatory and/or Advertised deployment'
switch ($LASTEXITCODE) {
  1 { 'You selected Mandatory.' }
  2 { 'You selected Advertised.' }
  3 { 'You selected Both.' }
}