Try\Catch not trapping error

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 5 years and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
Shelltastic
Posts: 65
Last visit: Mon Feb 19, 2024 11:31 am

Try\Catch not trapping error

Post by Shelltastic »

I am using the following code to bulk add members to a distribution list. The try\catch is not trapping the error, although I am able to see the error in the console when I debug the program. It just continues processing the code even if I use "-ErrorAction Stop".

foreach ($item in $users)
{
try
{
Add-DistributionGroupMember -Identity $TargetDL -Member $item -erroraction stop
}
catch
{
[System.Windows.Forms.MessageBox]::Show($PSItem, 'Error')
}
}
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Try\Catch not trapping error

Post by jvierra »

What error are you getting?
User avatar
Shelltastic
Posts: 65
Last visit: Mon Feb 19, 2024 11:31 am

Re: Try\Catch not trapping error

Post by Shelltastic »

For this specific error, its a duplicate error. However, I would assume when any error is thrown the behavior would be the same since I am already specifying -ErrorAction stop and it's not working. Screen shot below..

https://1drv.ms/u/s!AgBAbImA7NSlsxyQnBdWjslyeHA8
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Try\Catch not trapping error

Post by jvierra »

Many errors cannot be trapped.

See: https://blogs.technet.microsoft.com/hey ... owershell/
User avatar
Shelltastic
Posts: 65
Last visit: Mon Feb 19, 2024 11:31 am

Re: Try\Catch not trapping error

Post by Shelltastic »

Ok, I did already read that post in my searches this morning. Looks like we came across the same one. I'll have to find another way to go about this then, thanks.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Try\Catch not trapping error

Post by jvierra »

You need to start by not sending bad user ids. They must be the correct type and must exist. The strings cannot have odd characters or spaces.

You can only use these types of names:


•Alias
•Distinguished name (DN)
•Canonical DN
•Email address
•GUID
This topic is 5 years and 11 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked