PowerShell: Find many users using their name

Last week, I showed you how I looked up a single user in Active Directory, using the Get-ADUser cmdlet. I noted that I had an issue with finding some users due to spelling errors. This wasn’t a problem when I was doing them individually, but I soon found myself needing to do the same for more than a hundred users.

Not only did I now need to automate the search (as I’ve demonstrated previously), but I also needed to to catch it when no result was returned. This latter point was the challenging bit. We start by defining our users, create a ForEach-loop, and then add in an if/else-check. As a check to verify that I have found the correct user, I output both samAccountName and name, which gives me a script that looks like this:

$Users = @("*Surname001";
"*Surname002";
"*Surname003")
ForEach ($User in $Users){
if ( $x = Get-ADUser -Filter {displayName -like $User } | select samAccountName, name){
$x}
else {
'nothing found'}
}


Posted

in

by

Comments

By posting a comment, you consent to our collecting the information you enter. See privacy policy for more information.

This site uses Akismet to reduce spam. Learn how your comment data is processed.