Test an Active Directory User

I have recently been working on automating our new hire process with PowerShell (at least the Exchange/AD aspects).  I found myself needing a simple function that would return true or false based on whether a specified username is in use or not.  I needed this for validating username parameters in my other functions, as well for my function that would generate a valid username from a first, middle, and last name that wasn’t already in use.

Here is what I came up with:

Pretty simple, just tries tries to Get-ADUser with ErrorAction set to stop so errors are terminating, then catches the specific ADIdentityNotFound exception.  The function returns true if the user is found without error, and false if the user doesn’t exist.  All other errors are thrown.

Full function, with some verbose logging and my logging functions utilized can be found here: GitHub ScriptCenter

 

Leave a Reply

Your email address will not be published. Required fields are marked *