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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With