62
$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?

1
  • $UserInput = Read-Host "Enter any value:" if $UserInput not match with element of $InputArray, then again ask for correct entry, which is in array. Commented Jun 6, 2013 at 15:05

3 Answers 3

93

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)
Sign up to request clarification or add additional context in comments.

1 Comment

These checks can also be inverted using -notcontains and -notin.
11

I understand that you are learning but you need to use Google-fu and the documentation before coming here.

$inputArray -contains $userinput

2 Comments

'a','b','c' -contains (Read-Host)
:) Yes, didn't want to confuse a beginner.
10

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.