Andr0mega
Andr0mega

Reputation: 65

Powershell multiple If-Statements with loop

I have to check for multiple array entries in an if statement.

if (($Right.IdentityReference -eq $User) -or ($Right.IdentityReference -eq ("Domain\" + $GroupArrayList[0])) -or ($Right.IdentityReference -eq ("Domain\" + $GroupArrayList[1])))

This will continue with $GroupArrayList[2], $GroupArrayList[3], ...

Is there any way how I can go trough every entry of the array? I can't write every position down because the array size is dynamic. How can I create such a loop?

Upvotes: 0

Views: 305

Answers (3)

user6811411
user6811411

Reputation:

As you're ORing the comparison's why not testing if -in array?

if ($Right.IdentityReference -in 
        $User,
        ("Domain\" + $GroupArrayList[0]),
        ("Domain\" + $GroupArrayList[1]) ) {

Upvotes: 1

Theo
Theo

Reputation: 61068

I don't think you even need a loop for that, but instead use the -contains operator like this:

if (($Right.IdentityReference -eq $User) -or ($GroupArrayList -contains ($Right.IdentityReference -replace '^Domain\\',''))

You simply strip off the Domain\ from the $Right.IdentityReference and see if the string that remains can be found in the $GroupArrayList array.

Upvotes: 1

Michael B.
Michael B.

Reputation: 574

You can use a Foreach

Foreach ($ArrayItem in $GroupArrayList) {
    if (($Right.IdentityReference -eq $User) -or ($Right.IdentityReference -eq ("Domain\" + $ArrayItem))) {
        # Do stuff
    }
}

The variable $ArrayItem will refer to your $GroupArrayList[2], $GroupArrayList[3],...

Upvotes: 1

Related Questions