2

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
1
  • 2
    you can always use -match: $_.UserPrincipalName -match "a-|falkon|test|whiteboard|CSC". Since it looks like you're querying AD, you can use the filter to search for those keywords at runtime as well. Commented Feb 28, 2022 at 22:41

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Unfortunately that didn't return anything. I am not too familiar with the -filter parameter either.
@kooleosis if it didn't return anything is likely because there are no users under the "SearchBase" OU which's userprincipalname is "not like" the wildcards in $notLike

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.