Understanding the statement "exit"

by Jun 27, 2014

PowerShell supports the keyword "exit" which is a scope-based. It may work much differently than you assumed it would.

Let's take a function like this one:

function test 
{
  'A'
  exit 
  'B'
}

When you save this function in a script and call the function from the script, this is what you get:

PS> C:\Users\Tobias\Documents\PowerShell\test12343.ps1
A

So "exit" has exited the function prematurely. However, when you did not save the script, or when you call the function interactively, your entire PowerShell host will close.

"Exit" will leave the caller context, not just the function. So if your saved script had looked like this, you'd maybe up for another surprise:

function test 
{
  'A'
  exit 
  'B'
}

'Start'
test
'Stop'

Now the result looks like this:

PS<> C:\Users\Tobias\Documents\PowerShell\test12343.ps1
Start
A

As you notice, the "Stop" statement was not executed anymore. "Exit" has exited the function AND the caller scope. This is why it will close your PowerShell if you call the function interactively (because then, your caller scope is the host itself).

So what is "exit" used for? You can use it to set a numeric error level when a script is done. This numeric error level can then be read by the caller, so if you schedule a PowerShell script with the Task Scheduler, or run it from a batch file via powershell.exe, then any number you specify after exit will turn into the exit code of your script and surface as %ERRORLEVEL% in your batch file.

Twitter This Tip! ReTweet this Tip!