$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?
Check Elements of an Array of String in PowerShellThe “Contains()” method is utilized for checking if a particular string exists as an array element. To utilize this method, specify the string value as a parameter in the “Contains()” function.
For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.
PowerShell ArraysAn array is a type of a variable. It is a set of components (array elements) arranged in a certain order. Elements of the array are numbered sequentially, and you access an element using its index number. As you can see, in this case, PowerShell created an array (System.
Retrieve items from an Array To retrieve an element, specify its number, PowerShell automatically numbers the array elements starting at 0. Think of the index number as being an offset from the staring element. so $myArray[1,2+4..
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)
I understand that you are learning but you need to use Google-fu and the documentation before coming here.
$inputArray -contains $userinput
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With