$InputArray = @(a,e,i,o,u,1,2,3,4,5)
$UserInput = "Enter any value:"
How can we check that $UserInput is in $InputArray or not and prompt for correct input?
$InputArray = @(a,e,i,o,u,1,2,3,4,5)
$UserInput = "Enter any value:"
How can we check that $UserInput is in $InputArray or not and prompt for correct input?
Use the -contains operator:
$InputArray -contains $UserInput
With more recent PowerShell versions (v3 and above) you could also use the -in operator, which feels more natural to many people:
$UserInput -in $InputArray
Beware, though, that either of them does a linear search on the reference array ($InputArray). It doesn't hurt if your array is small and you're not doing a lot of comparisons, but if performance is an issue using hashtable lookups would be a better approach:
$validInputs = @{
'a' = $true
'e' = $true
'i' = $true
'o' = $true
'u' = $true
'1' = $true
'2' = $true
'3' = $true
'4' = $true
'5' = $true
}
$validInputs.ContainsKey($UserInput)
-notcontains and -notin.Interesting hack I use all the time in powershell: the echo command will convert unquoted arguments into a string array.
(echo a b c) -contains 'a'
# outputs True / returns $true
This is WAY EASIER than typing @('a','b','c'). My fingers have never gotten fast at typing ' after every 2nd or 3rd character.