Search code examples
powershellpowershell-2.0

How to exit powershell from a sourced script?


Consider "outer.ps1":

"in outer.ps1"
. .\inner.ps1
"in outer.ps1 after sourcing inner.ps1"

that sources "inner.ps1" which just exits:

exit 0

When I run "outer.ps1" the output indicates that the exit only returns from "inner.ps1":

in outer.ps1
in outer.ps1 after sourcing inner.ps1

Is it possible to exit the powershell process from inner.ps1? I don't want to throw an exception, this would be a normal termination.


Solution

  • You can use this instead:

    [Environment]::Exit(0)
    

    But be warned - it will exit the PowerShell console completely. That's a pretty big hammer. :-)

    A better way is to use a trap handler in outer.ps1 e.g.:

    trap { exit 0 }
    

    And in inner.ps1 do a throw e.g.:

    throw "Inner.ps1 done!"