Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell 'Or' Statement

Tags:

powershell

I'm trying to go through the Active Directory, and grab users who meet a certain criteria. I want to get users have either Manager A or Manager B, but I'm not sure how to implement the or statement. Here's my code:

Get-ADUser -Filter * -Properties country, extensionattribute9 | if (extensionattribute9 -eq 'Smith, Joe') or (extensionattribute9 -eq 'Doe, John') {select extensionsattribute9, country}

In this code, it doesn't recognize extensionattribute9, which gives you the user's manager.

I also tried attempted using where instead of if, but to no avail.

like image 588
Luke K Avatar asked Jun 23 '16 13:06

Luke K


1 Answers

The operator is -or, not or. See about_Logical_Operators. Also, if statements don't read from the pipeline. Either put the if statement in a ForEach-Object loop:

... | ForEach-Object {
  if ($_.extensionattribute9 -eq 'Smith, Joe' -or $_.extensionattribute9 -eq 'Doe, John') {
    $_ | select extensionsattribute9, country
  }
}

or use a Where-Object statement instead:

... | Where-Object {
  $_.extensionattribute9 -eq 'Smith, Joe' -or
  $_.extensionattribute9 -eq 'Doe, John'
 } | Select-Object extensionsattribute9, country

And you can't use property names by themselves. Use the current object variable ($_) to access properties of the current object.

For checking if an attribute has one of a given number of values you can also use the -contains operator instead of doing multiple comparisons:

'Smith, Joe', 'Doe, John' -contains $_.extensionattribute9
like image 159
Ansgar Wiechers Avatar answered Sep 23 '22 20:09

Ansgar Wiechers