Error handling in ISE and inside a script

Hi,

I wrote the function below to add some mail addresses on a distribution group.
The problem is that running it line by line on Windows Azure Module PowerShell (connected to Exchange Online module) it works normally, and trying to run it on PowerShell ISE or inside a script… it doesn’t.
How to make this cmdlet (Add-DistributionGroupMember) stop on an error for me to handle with Try/Catch?

function Add-Mails{ Param( [Parameter(Mandatory=$True, ParameterSetName="List")] [String] $List ) foreach ($Parent in $Parents){ $ErrorActionPreference = "Stop"

Try{
Add-DistributionGroupMember -Identity $List -Member $Parent
}
Catch{
$MailsNotAdded += $Parent
}

$ErrorActionPreference = “Continue”
}
Write-Host
Write-Host $MailsNotAdded.Count “mail(s) not add(ed) in the grupo.”
Write-Host
Write-Host “Mails not added:”
$MailsNotAdded
}

Hi Vandrey,

When you say it “works normally” on Azure, do you mean that it throws an exception and the code inside of your catch executes? I just want to make sure, but that’s what I would expect it to do.

What is it doing inside of the ISE? I’m thinking if it’s doing something like ignoring your $ErrorActionPreference it will just write to the error stream and continue without hitting your catch. If that is the case, you can check the value of $? to see if it is $false and throw an exception manually if that’s the case.

It’s not pretty, but until you figure out why the behavior is different it might get you up and running.

-Adam