PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.


As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Why "exit" can kill PowerShell

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!

Copyright 2012 PowerShell.com. All rights reserved.