Using PowerShell to Search for Specific Users in Active Directory without Knowing their Exact Information

You're looking for a user in your Active Directory environment who goes by the nickname of JW. You know that's the user's initials and you need to find their AD user account.

Typically you'd use the Identity parameter, but that parameter doesn't allow wildcards:

1Get-ADUser -Identity j*w*

finduser1.jpg

Verifying wildcard's are not allowed on the Identity parameter of Get-ADUser:

1help Get-ADUser -Parameter identity

finduser4.jpg

What you'll need to do is use the Filter parameter instead:

1Get-ADUser -Filter {name -like 'j*w*'}

finduser2.jpg

The previous results were close to what you wanted, but not exactly. It included users like Jo Brown since his name also matches the search criteria that was provided. This time let's try a compound filter and specify GivenName's that start with J and Surname's that start with W:

1Get-ADUser -Filter {GivenName -like 'j*' -and Surname -like 'W*'}

finduser3.jpg

The previous example is much, much better than using the Where-Object cmdlet to filter with since the previous example follows the best practice of filtering early or filtering left.

This is how NOT to accomplish the task because it is less efficient:

1Get-ADUser -Filter * | Where-Object {$_.GivenName -like 'j*' -and $_.Surname -like 'W*'}

finduser5.jpg

Since I've already told you that the previous example is less efficient, I'll now show you that it's less efficient:

1Measure-Command {Get-ADUser -Filter {GivenName -like 'j*' -and Surname -like 'W*'}}
2
3Measure-Command {Get-ADUser -Filter * | Where-Object {$_.GivenName -like 'j*' -and $_.Surname -like 'W*'}}

finduser6.jpg

As you can see in the previous results, the example that used the Filter parameter took about 12 milliseconds to complete and the example that used the Where-Object cmdlet for the filtering took approximately 310 milliseconds to complete. There are a total of 305 Active Directory user accounts in the test environment that these examples were run against. The performance of the Where-Object example would be worse if more Active Directory user accounts existed in the environment.

The examples shown in this blog have been demonstrated on a Windows 8.1 client machine with the RSAT (Remote Server Administration Tools) installed. The client machine is part of a domain and the domain controllers are running Windows Server 2012 R2.

µ