PowerShell exit() kills shell and ISE

Gargravarr picture Gargravarr · Aug 15, 2016 · Viewed 9.9k times · Source

So I've written a series of functions and inserted them into a PS Module (.psm1). One of which is a simple ErrorAndExit function that writes a message to STDERR and then calls exit(1);, a habit to allow easy redirection of error messages. While debugging my script, in either the normal PowerShell or ISE, if I call a function that in turn calls ErrorAndExit, it not only exits the script, but exits the entire PowerShell process. Both the terminal and ISE die immediately. The terminal, I might just understand, but ISE?! The most frustrating part is, of course, that I cannot see the error message before the window disappears.

I believe this has something to do with how I'm debugging - I've defined a lot of functions that happen in a chain, and have commented out the call to start the chain. I'm importing the script and calling the functions from the prompt. As the script is designed for automation, killing the whole PS process will not be a problem in actual use, but I need to see what the debug output is.

The function in question, in Common.psm1:

function errorAndExit([string]$message)
{
    logError($message);
    exit(1);
}

Where logError passes $message to Write-Error. An example function where this call causes PS or ISE to die:

function branch([string]$branchName, [int]$revision, [string]$jenkinsURL, [switch]$incrementTrunk)
{
    Set-Variable -Name ErrorActionPreference -Value Stop;
    log("Script starting, parameters branchName=$branchName, revision=$revision, jenkinsURL=$jenkinsURL");
    if (-not ($branchName -match "\d{4}\.\d{2}\.\d"))
    {
        errorAndExit("Provided branch name $branchName is not a valid YYYY.MM.R string");
    }
...

My Common.psm1 module is being imported with a simple Import-Module -Force "$PSScriptRoot\Common";. When called from the PS prompt:

PS C:\Windows\system32> branch -branchName abc

causes either PowerShell or ISE to exit completely.

I am coming to PowerShell from a Bash mentality and have written scripts as such (getting used to passing objects however), but this is not behaviour I would expect from any scripting language.

Answer

Christopher G. Lewis picture Christopher G. Lewis · Aug 15, 2016

In Powershell ISE, the exit command closes the entire IDE, not just the current command tab.

https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/13223112-would-be-better-if-the-exit-command-in-powershell

Your use of exit is a little flawed in your errorAndExit function. As mentioned, either a throw or a return $false and evaluating the results would be a better bet.