April 13, 2010

How to trap an “Object already exists” error setting Active Directory properties

Sometimes when you create a new user, a new group or add a new member to a group you don’t want you script to end if the object already exist or the user is already a member.

It’s the setinfo() method that return this exception (error). So simply add a Try Catch  before and after your setinfo() like this :

Try {
	$newUser.SetInfo()
	}
Catch [System.DirectoryServices.DirectoryServicesCOMException] {
	If ($_.exception.ErrorCode -eq -2147019886) {
		Write-Warning "The object already exists."
		}
	else {
		Throw $_
		}
	}

No comments:

Post a Comment