Validation 使用PowerShell进行用户输入验证

Validation 使用PowerShell进行用户输入验证,validation,powershell,user-input,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 &quo

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

以下是脚本的基本思想:

$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
}
问题在于,它只确认字符串是否为空/null,并且所有其他输入都将使脚本退出WHILE循环并继续执行if-ELSE语句

为什么?


例如:

如果我输入“yes”、“yes”、“yes”、“y”、“y”或与此类似的任何其他变体,应用程序将跳过/退出WHILE语句并继续执行If语句,按预期执行所需操作。如果我不输入任何内容(将字符串保留为null/empty),它将按预期留在While循环中。但是,任何其他输入都会导致应用程序跳过/退出WHILE语句并继续执行ELSE语句,这不是我想要的

我用-eq,-ieq,-ceq,-like,-ilike,-ne,-ine,-notlike和-inotlike尝试过这个方法 我甚至一直在和-和-或操作员玩游戏,希望可能是我把设置搞砸了


不幸的是,所有人都给出了相同的结果。

由于条件语句的第一部分
,只有当$answer为空时,这才有效$回答并

$answer = Read-Host "Are you sure you wish to continue? [Y]es or [N]o"
While (!($answer) -and 
       (($answer.Substring(0,1).ToUpper() -ne 'Y') -or
        ($answer.Substring(0,1).ToUpper() -ne 'N')))
{
   $answer = Read-Host "You entered an invalid response.`r`nPlease enter [Y]es or [N]o"
}

( ... )

您需要将其更改为“或”,如下所示:
同时(!$answer-OR($answer-ine“y”-和$answer-ine“yes”-和$answer-ine“n”-和$answer-ine“no”)
使用内置的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
)。

Oh。我不知道这会引起问题。非常感谢这帮了大忙。