Gargravarr Gargravarr - 1 year ago 68
PowerShell Question

PowerShell exit() kills shell and ISE

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

, 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)

. 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 Source

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

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.