Why "exit" can kill PowerShell

by Apr 28, 2015

Occasionally, there are misunderstandings how "exit" works. Take this example:

function abc
{
  'Start'

  exit 100

  'Done'
}

abc

When you run this script, the abc function is called, then aborted. You will see only "Start", but not "Done", and $LASTEXITCODE contains the value 100. But is this the truth?

When you now run the abc function interactively from within the interactive PowerShell console, the function aborts again, but this time, PowerShell also closes. Why?

"Exit" aborts code at caller scope. When you run a script, the script is aborted, but PowerShell continues to run. When you run the function interactively, your interactive PowerShell is aborted, which happens to be the global scope, and since there is no higher scope left, PowerShell closes.

To make this point a little more evident, take the previous sample script, and add a little to it:

function abc
{
  'Start'

  exit 100

  'Done'
}

'Function starts'
abc
'Function ends' 

As you will discover, "exit" in reality does not abort the abc function. Instead, it aborts the entire script. Neither will you see "Done" nor "Function ends".

Use "exit" with care! It should only be used to abort a script and return control to the caller.

Twitter This Tip! ReTweet this Tip!