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

link|improve this question

68% accept rate
feedback

2 Answers

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

link|improve this answer
Yeah I didn't realize that the trap syntax was from the first version of PowerShell. – leeand00 Mar 31 '11 at 21:04
feedback

I use this function to test for AD objects:

function Test-QADObject {
 [CmdletBinding()]
 param(
      [Parameter(Position=0, Mandatory=$true)]
      [System.String]
      $Identity
 )
(Get-QADObject $Identity -DontUseDefaultIncludedProperties `
-WarningAction SilentlyContinue -ErrorAction SilentlyContinue `
-SizeLimit 1) -ne $null

}

It's from here but I can't find the direct link.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.