Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you check if a variable is in an array in PowerShell?

I am attempting to create an audit of mailbox permissions in powershell and would like to remove specific accounts from the output within the powershell script rather than manually afterwards.

In order to do this I am looking for a way to compare the contents of an array against a single string in powershell.

For example, if I was to declare an array:

$array = "1", "2", "3", "4"

I then want to find a way to do something like the below:

$a = "1"
$b = "5"

if ($a -ne *any string in $array*) {do something} #This should return false and take no action

if ($b -ne *any string in $array*) {do something} #This should return true and take action

I am at a loss for how this would be accomplished, any help is appreciated

like image 676
Ethan Field Avatar asked Feb 01 '17 17:02

Ethan Field


1 Answers

You have several different options:

$array = "1", "2", "3", "4"

$a = "1"
$b = "5"

#method 1
if ($a -in $array)
{
    Write-Host "'a' is in array'"
}

#method 2
if ($array -contains $a)
{
    Write-Host "'a' is in array'"
}

#method 3
if ($array.Contains($a))
{
    Write-Host "'a' is in array'"
}

#method 4
$array | where {$_ -eq $a} | select -First 1 | %{Write-Host "'a' is in array'"}
like image 90
Esperento57 Avatar answered Sep 30 '22 19:09

Esperento57