Powershell – Trapping only exceptions that occur when an active directory user already exists using the New-QADUser cmdlet

active-directorypowershell

If I only want to trap an exception when a user already exists, what type of Exception should I trap?

for instance:

 [UserAlreadyExistsException]
 trap{
    #forget about it....
 }
 [AnyOtherException]
 trap{
    #PANIC!
 }
 $newUser = New-QADUser -name $line.UserID -ParentContainer 'OU=Symetra,DC=CI3DOMAIN,DC=local' -samAccountName $line.UserID -UserPassword 'p' -DisplayName $line.APPROVER -Department $line.Department -Description "$approver from $department" -ErrorAction SilentlyContinue

Update!

I was just notified here that the exception thrown is system.DirectoryServices.DirectoryServicesComException

Best Answer

You could use the Try, Catch block like the following.

try
{
   New-ADUser "FAKEACCOUNT"
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]
{
   #forget about it....
}
catch
{
   #PANIC!
}

Note: I'm not positive the New-QADUser cmdlet throws the same exception, but the above code works for the New-ADUser cmdlet.

This link may help you decipher the specifics of your situation: http://blogs.msdn.com/b/adpowershell/archive/2009/03/25/error-reporting-in-active-directory-powershell.aspx

Related Topic