Aniruddha
Aniruddha

Reputation: 1039

Multiple condition in where clause

When I execute below code, I get an error as : A parameter cannot be found that matches name or. How can I get user list who don't have abc.com or xyz.com in their email address?

Get-ADGroupMember -Identity "AQ" -Recursive | where objectClass -eq 'user' | Get-ADUser -Properties *,  "msDS-UserPasswordExpiryTimeComputed", PasswordNeverExpires |

where  mail -notmatch "@abc.com" -or "@xyz.com" | 
Select-Object @{Label = "SAM Account Name";Expression = {$_.SamAccountName}}

Upvotes: 1

Views: 662

Answers (3)

Manuel Batsching
Manuel Batsching

Reputation: 3596

The curly braces (actually a scriptblock with the filter script) can not always be skipped with Where-Object.

You can do Where-Object objectClass -eq 'user' but everything that involves more than a single operator requires to be written as a filter script:

where {$_.mail -notmatch "@abc.com" -or "@xyz.com" }

Now this logic doesn't work, as this is equivalent to the following statement:

where {($_.mail -notmatch "@abc.com") -or $true }

So your where clause is true, regardless of the result of the -notmatch operation. You want two -notmatch operations instead:

Where-Object - { $_.Mail -notmatch '@abc.com' -and $_.Mail -notmatch '@xyz.com' }

Depending on the amount of email addresses, that you want to exclude in your filter script, you might want to use a different approach: Strip the user name from the email address and see, if this address appears in the array of email addresses that you want to exclude.

Where-Object { ( $_.Mail -replace '^[^@]+') -notin '@abc.com','@xyz.com','@foo.bar' }

Upvotes: 4

TobyU
TobyU

Reputation: 3908

You're missing some brackets around your where-clause:

where {objectClass -eq 'user'}

And this:

where {mail -notmatch "@abc.com" -or  "@xyz.com"}

Should look like that:

where {mail -notmatch "@abc.com" -or mail -notmatch "@xyz.com"}

Please rethink the logic of your second where since it will always be true.

Upvotes: 1

4c74356b41
4c74356b41

Reputation: 72171

for multiple conditions use full syntax:

where-object { $_.property -eq $b -and $_.otherproperty -match $a }

Upvotes: 2

Related Questions