我的自定义用户输入验证方法无法按预期工作。
这是脚本的基本思想:
$answer = Read-Host "Are you sure you wish to continue? [Y]es or [N]o"
while (!$answer -AND $answer -ine "y" -AND $answer -ine "yes" -AND $answer -ine "n" -AND $answer -ine "no") {
$answer = Read-Host "You hand entered an invalid response.`nPlease enter [Y]es or [N]o"
}
if ($answer -ieq "yes" -OR $answer -ieq "y") {
do action
}
else {
don't do action
}
问题是它只确认字符串是否为 empty/null
,所有其他输入将使脚本退出 WHILE 循环并继续执行 IF-ELSE 语句。
为什么?
例子:
如果我输入“yes”、“YES”、“Yes”、“y”、“Y”或任何其他类似的变体,应用程序将跳过/退出 WHILE 语句并继续执行 IF 语句,执行预期的预期行动。如果我不输入任何内容(保留字符串 null/空),它将按预期保留在 While 循环内。但是,任何其他输入都会导致应用程序跳过/退出 WHILE 语句并继续执行 ELSE 语句,这不是我想要的。
我已经尝试使用 -eq、-ieq、-ceq、-like、-ilike、-ne、-ine、-notlike 和 -inotlike 我什至一直在玩弄 -AND 和 -OR 运算符,希望我搞砸了那个设置。
不幸的是,所有人都给了我相同的结果。
最佳答案
使用内置的 PowerShell 选择工具。示例:
$choices = [Management.Automation.Host.ChoiceDescription[]] @(
New-Object Management.Automation.Host.ChoiceDescription("&Yes","Do whatever.")
New-Object Management.Automation.Host.ChoiceDescription("&No","Do not do whatever.")
)
$choice = $Host.UI.PromptForChoice("Are you sure?","This will do whatever.",$choices,1)
您可以轻松地添加到选择列表中。如果您选择第一个选项,$choice
变量将设置为 0
,第二个选项为 1
,依此类推。 PromptForChoice
方法的最后一个参数确定默认选择(即,如果您只按 Enter
)。
关于validation - 使用 PowerShell 进行用户输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45422359/