Why is the error handling in powershell ISE and command line different?

572 Views Asked by At

I have a powershell script that uses azure cli to log in and do a bunch of other stuff. At the beginning I set

$ErrorActionPreference = "Stop"

When I run the script in the ps ISE and the azure login fails the error is displayed and execution stops, just as expected. But when I run the script from the ps command line (or from a batch that calls the script) the error is displayed - and execution continues?!

I tried with a try/catch, same thing there, the catch is only hit in the ISE but not from the command line.

This seems VERY strange to me. Anyone has an idea what causes this and how I can get around of it? Rebooting didn't help :-)

1

There are 1 best solutions below

1
On

this answer might be a little to late, but i had the same problem with a connection to EWS. It worked fine with the Powershell ISE, but it didnt work with the Powershell.exe.

After hours of testing i finally figured out that there is a difference between Powershell and the ISE in how they handle errors.

$errorlength = $Error.Count
$EmailAddress= Get-Mailbox -Identity $shortname.SamAccountName| Select-Object WindowsEmailAddress
if($errorlength -lt $Error.Count){
    throw "Bad thing happened"
}

My problem was that there where some Mailboxes in our adress list which are in the office365 cloud an some on the Exchange server. Somehow Powershell ISE terminated on the error and Powershell itself did not.

If your error also occures at the excact same position all the time this should work for you too.

It forces the program to terminate if the errorcounter goes up.