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:
# Tries to get information about the specified user # Returns true if found and false if it catches the specific ADIdentityNotFound exception # Terminates if it finds any other error try { $user = Get-ADUser -Identity $username -ErrorAction Stop $true } catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { $false } catch { # Handle all other errors throw $_ }
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