Home > database >  PowerShell Multiple -and operators?
PowerShell Multiple -and operators?

Time:03-01

Is there a simpler way to do this? Or does it require me to type out each -and/-notlike for each of the criteria?

Where-Object {$_.DistinguishedName -like "<Enter Domain OU>"} |
Select-Object UserPrincipalName | 
Where-Object `
{$_.UserPrincipalName -notlike 'a-*' `
-and $_.UserPrincipalName -notlike 'falkon*' `
-and $_.UserPrincipalName -notlike 'test*' `
-and $_.UserPrincipalName -notlike '*whiteboard*' `
-and $_.UserPrincipalName -notlike '*CSC*' `
-and $_.UserPrincipalName -notlike '*autopilot*'} |
Sort-Object UserPrincipalName

CodePudding user response:

Unfortunately, he can't use -match in an AD filter, but he can use -notlike. The poster can drop the backticks and use operators to continue lines at least. Distinguishedname can't be in an AD filter.

get-aduser -filter "UserPrincipalName -notlike 'a-*' -and
  UserPrincipalName -notlike 'falkon*' -and
  UserPrincipalName -notlike 'test*' -and
  UserPrincipalName -notlike '*whiteboard*' -and
  UserPrincipalName -notlike '*CSC*' -and
  UserPrincipalName -notlike 
  '*autopilot*'" -searchbase 'DC=stackoverflow,DC=com' -resultsetsize 1

CodePudding user response:

You can do the following string manipulation to build an LDAP Filter for less verbosity on your script and to leverage Active Directory Filtering capabilities.

Worth mentioning, as more users are under the SearchBase Organizational Unit the faster -Filter / -LDAPFilter becomes compared to Where-Object.

$ou = 'OU=some,OU=ou,DC=some,DC=domain'
$notLike = 'a-*', 'falkon*', 'test*', '*whiteboard*', '*CSC*', '*autopilot*'
$filter = '(&(!userprincipalname={0}))' -f ($notLike -join ')(!userprincipalname=')

$params = @{
    SearchBase  = $ou
    SearchScope = 'OneLevel' # Or SubTree for all child OUs under `$ou`
    LDAPFilter  = $filter
}
Get-ADUser @params | Sort-Object UserPrincipalName
  • Related