简体   繁体   中英

User input Validation using PowerShell

My custom user input validation method is failing to work as expected.

Here is the basic idea of the script:

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

The problem is that it only confirms if the string is empty/null and all other inputs will have the script exit the WHILE loop and proceed to the IF-ELSE statements.

Why?


Example:

If I input "yes", "YES", "Yes", "y", "Y" or any other similar variation to this, the application will skip/exit the WHILE statement and proceed to the IF statement, performing the desired action as intended. If I do not input anything (leaving the string null/empty), it will stay inside the While loop as intended. However, any other input will cause the application to skip/exit the WHILE statement and proceed to the ELSE statement, which is not what I want.

I have tried this using -eq, -ieq, -ceq, -like, -ilike, -ne, -ine, -notlike, and -inotlike I have even been playing around with the -AND and -OR operators in hopes that maybe I messed up on that setup.

Unfortunately, all gave me the same results.

This will only work when $answer is null because of the first part of your conditional statement !$answer AND ...

You need to change it to an "OR" as follows: while (!$answer -OR ($answer -ine "y" -AND $answer -ine "yes" -AND $answer -ine "n" -AND $answer -ine "no"))

Use the built-in PowerShell choice facility. Example:

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

You can easily add to the list of choices. The $choice variable will be set to 0 if you choose the first option, 1 for the second, and so forth. The last parameter of the PromptForChoice method determines the default choice (ie, if you just press Enter ).

$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"
}

( ... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM