validation - 使用 PowerShell 进行用户输入验证

标签 validation powershell user-input

我的自定义用户输入验证方法无法按预期工作。

这是脚本的基本思想:

$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/

相关文章:

java - 重复注释 - hibernate validator

excel - 在事件的 Excel 文档中使用 VBA 从 powershell 连接到 Excel

regex - Powershell 正则表达式用连字符替换下划线

c++ - 如何对控制台输入类进行单元测试?

javascript - 如何根据输入值创建新用户

jquery 表单验证无法使用页面中的选项卡

matlab - 如何在MATLAB中验证概率神经网络给出的输出?

r - 在 R 程序中询问用户输入的正确方法是什么?

ruby - 如何使用 minitest 测试实例级 Sequel::Model 验证

.net - 错误 MSB3147 : Could not find required file 'setup.bin' Publish to Local FAILURE