简体   繁体   中英

Using and/or operators in powershell command

I want this query to only return enabled users who have a name matching "marketing" or "accounting". However, when I run this it's returning disabled users as well? What am I missing? From my research this is what I came up with but it's not working.

Get-ADuser -filter {(Name -like "*marketing*") -or (Name -like "*accounting*") -and (Enabled -eq "true")} -Properties *

Thanks for any advice!

In Boolean logic in general, AND takes precedence over OR. In other words, AND operations are evaluated first, before OR.

So that command is really asking for accounts where either:

  1. The name contains "marketing", or
  2. The name contains "accounting" and is enabled

To get the results you want, you need to enclose the entire -or expression in parentheses to force it to evaluate it first, and leave the -and outside the parentheses:

Get-ADuser -Filter {(Name -like "*marketing*" -or Name -like "*accounting*") -and Enabled -eq "true"} -Properties *

As mentioned in the comments above, the documentation tells us that the -Filter parameter is technically a string. So if you give it a script block ( { } ), PowerShell does some translation on it to convert it to a string. Sometimes that translation can go wrong, so you're often better off giving it the string it should be, which would look something like this:

Get-ADuser -Filter "(Name -like '*marketing*' -or Name -like '*accounting*') -and Enabled -eq 'true'" -Properties *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM