简体   繁体   中英

PowerShell: Catch Exception of Active Directory Cmdlets

I have a problem concerning Exceptions in Powershell. For some reason they don't get caught.

Try { 
    Add-ADGroupMember -Identity $GroupToModify.ObjectGUID -Members $user
} Catch [ADIdentityNotFoundException] {
    #message goes here
}

when trying to add a user from a different Domain it outputs:

Get-ADUser : Cannot find an object with identity: 'CN=user,OU=users,
OU=J2,OU=sites,DC=asia,DC=domain,DC=com' under: 'DC=europe,
DC=domain,DC=com'.
At myscript.ps1:753 char:14
+     $adMember = Get-ADUser $user
+                 ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (CN=user...s,DC=com:ADUser) 
[Get-ADUser], ADIdentityNotFoundException
+FullyQualifiedErrorId :
ActiveDirectoryCmdlet:
Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,
Microsoft.ActiveDirectory.Management.Commands.GetADUser

You have 2 options. Use -ErrorAction Stop on each cmdlet you want to trigger an exception:

Try { 
    Add-ADGroupMember -Identity $GroupToModify.ObjectGUID -Members $user -ErrorAction Stop
} Catch [ADIdentityNotFoundException] {
    #message goes here
}

or specify $ErrorActionPreference = "Stop" at beginning of PS session to achieve same result for all subsequent cmdlets.

Check out this error handling guide from Hey Scripting guy, it really helped me understand ho to use catch statements. http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/11/hey-scripting-guy-march-11-2010.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM