Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check whether input value is in array or not (Powershell)

Tags:

powershell

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

like image 427
Krish Avatar asked Jun 06 '13 15:06

Krish


People also ask

How do you check if a value is present in an array PowerShell?

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.

How do you check if an array has a certain value?

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.

Is variable array PowerShell?

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.

How do I read an array in PowerShell?

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..


2 Answers

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) 
like image 168
Ansgar Wiechers Avatar answered Oct 27 '22 23:10

Ansgar Wiechers


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

$inputArray -contains $userinput 
like image 23
ravikanth Avatar answered Oct 27 '22 23:10

ravikanth