Berwari
Berwari

Reputation: 3

Filter out users that contains a word or character with Get-ADUser

I am trying to get a list of AD-Users in different domains but cannot find a way to exclude users that has "Health" in their name for an example.

This is how my query looks like as of now:

#$excludedusers = @('HealthMailbox123456')
Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' } | Select-object Samaccountname,surname,givenname | Where { $excludedusers -NotContains$_.Samaccountname }

As of now, "HealthMailbox123456" is excluded but only because I typed the entire name.

Is there a way to exclude every user having "Health" in their name?

Upvotes: 0

Views: 5494

Answers (1)

TobyU
TobyU

Reputation: 3908

Get-ADUser -Server $test -Credential $1cred -Filter {Enabled -eq $true -and SamAccountName -notlike "*health*"}

Using the -filter switch instead of piping the result set into Where-Object reduces the amount of data which has to be send from the Domain Controller to the local system and is therefore the faster option.

Upvotes: 3

Related Questions