PS without BS: Getting AD Users with a Filter

Recently, I was asked to get a list of admin accounts within multiple domains, however, all domains had a different or multiple naming standards. For those who use PowerShell and are familiar with get-aduser, you will know quickly that the filtering feature is limited with one wildcard option, being the *. You can't filter on single characters using the ? command.

So, what to do? Here's an example on how to use the switch command to filter user info...

Some notes from this example:

  • This script just grabs a lot of user metadata from AD, it can be trimmed down.
  • The switch command needs the wildcard argument, or it will take the wildcards as literal.
  • The ? is a single character wildcard. So in this case, I am looking for any 3 characters plus adm in places 4, 5, and 6.
  • Remember in AD, computers are people too. So I am saying that if the user account ends in a $, don't process it.

And the code... All it does it outputs the user name if the criteria is met, but you can do what you want with it... Feel free to test it as you like.

Note: Don't forget to change domain.local to your domain name.

$Users = get-aduser -filter * -server domain.local -Properties SmartcardLogonRequired, profilepath, lastLogonTimestamp, pwdLastSet, whenCreated, enabled, PasswordNotRequired, PasswordNeverExpires, accountExpires, physicalDeliveryOfficeName, title, initials, manager, Description

foreach($User in $Users)
{
$UserSam = $User.SamAccountName

switch -wildcard ($UserSam)
{
"???admin*" {$ProcessUser=$True}
"a-*" {$ProcessUser=$True}
}
if(!($UserSam.endswith("$")) -and ([bool]$ProcessUser)) {
write-host $UserSam
}
}

— If you like my blogs, please share it on social media, rate it, and/or leave a comment. —