I am attempting to prompt a user for input and then validate if the users input matches one of two different options, and will exit if a correct input was not given.
In the example, I am asking the user to enter 'BOB' or 'TOM' as valid inputs, however when I run this code I will always get the message 'Server type not entered correctly', even when I enter BOB as an input for the prompt.
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
If ($ServerType -ne "BOB" -Or $ServerType -ne "TOM")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
I have also tried
If (($ServerType -ne "BOB") -or ($ServerType -ne "TOM"))
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
However, when I only test for one value it works:
If ($ServerType -ne "BOB")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Any ideas why I might be getting this?
As in my comment, the logical operator in this case should be -and
but allow me to give you 2 examples where your validation could be improved.
-match
\ -notmatch
comparison operators, which allows the use of regex
:$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
if($ServerType -notmatch '^(bob|tom)$')
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
try
{
[validateset('bob','tom')]
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
}
catch
{
Write-Host -NoNewLine 'Server type not entered correctly'
}