Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Catch Exception of Active Directory Cmdlets

Tags:

powershell

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
like image 298
user3909653 Avatar asked Oct 23 '25 00:10

user3909653


1 Answers

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.

like image 149
Raf Avatar answered Oct 25 '25 22:10

Raf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!