Filter out users that contains a word or character

2019-08-27 15:18发布

问题:

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?

回答1:

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.