Error handling in ISE and inside a script

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Adam Platt Adam Platt 11 months, 4 weeks ago.

  • Author
  • #31186
    Profile photo of Vandrey Trindade
    Vandrey Trindade


    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{
    foreach ($Parent in $Parents){
    $ErrorActionPreference = "Stop"

    Add-DistributionGroupMember -Identity $List -Member $Parent
    $MailsNotAdded += $Parent

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

  • #31493
    Profile photo of Adam Platt
    Adam Platt

    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.


You must be logged in to reply to this topic.