Techibee.com

PowerShell: Search for a value in Array

If your array has a bunch of items and you would like to verify if the given string/number is found in the array, here is the quick tip for you.

There are actually 2 ways of doing it.

Using -In operators

$sample = @(1,2,3,4,5,6)
2 -in $sample # returns True
9 -in $sample # returns False
Using -in operator

Using Contains method on the array

Alternative to -in operator is using Contains method on the array object itself. This is equally useful.

Using Contains method

Both of the above approaches works well with strings too. In case you are using strings, note that Contains method is case sensitive and -in operators is not case-sensitive. Look at the below code for example.

$sample = @("one", "two", "three")
$sample.Contains("one") # returns True
$sample.Contains("oNe") # returns False
"one" -in $sample # returns True

"One" -in $sample # returns True

In case you want case sensitive search with -in operator use -cin instead

Hope this helps you.

Exit mobile version