Recommended practice for setting exitlevel

This forum can be browsed by the general public. Posting is limited to current SAPIEN license holders with active maintenance and does not offer a response time guarantee.
Forum rules
Only the original author and our tech personnel can reply to a topic that is created in this forum. If you find a topic that relates to an issue you are having, please create a new topic and reference the other in your post.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
Posts: 82
Joined: Tue Jul 10, 2012 10:37 am

Recommended practice for setting exitlevel

Post by owinsloe » Sun Jul 28, 2019 2:52 pm

Product: PowerShell Studio 2019 (64 Bit)
Build: v5.6.165
OS: Windows 10 Enterprise (64 Bit)
Build: v10.0.18362.0

Hi, I think I have been down this road before. Just after some assurance on what is the best practice for setting an exit level when exiting from a packaged console executable.

If I package a test script that simply contains ONE line...
exit 1
...and run it within a powershell CMD session, the exit level is not set. ie. equals 0

If I use the .net [environment]::exit(1), then it does get correctly set.

I've had issues in the past with correctly setting exits and I went away from using [environment]::exit(1) but can not recall why.

Is there a recommended or preferred method for exits?


User avatar
Site Admin
Posts: 234
Joined: Thu Jun 01, 2017 7:20 am

Re: Recommended practice for setting exitlevel

Post by brittneyr » Mon Jul 29, 2019 8:20 am

Using $script:ExitCode variable is the preferred way of returning a value to a parent process. The "[Environment]::Exit("N")" call terminates the process at that exit location. No further clean up and termination routines (or any other code elements) are executed. It should only be used in grave error conditions. Best practices suggest that the exit of an application should always happen controlled at the same location.
Brittney Ryn
SAPIEN Technologies, Inc.

User avatar
Posts: 82
Joined: Tue Jul 10, 2012 10:37 am

Re: Recommended practice for setting exitlevel

Post by owinsloe » Tue Jul 30, 2019 3:22 pm

Hi, thanks for the response but I fell into the trap of the most basic test...

Let's say we have a test.ps1 sitting in c:\temp and the only line in the script is;

Then I run up a CMD window and run powershell then;

I would expect to see $lastexitcode return 1 but it returns 0

After some searching (soul and net), I find that the above command is interpreted as a command and not running a process therefore the exitcode expression is lost.

To correctly run you need to;
powershell -file c:\temp\test.ps1

It can be a bit confusing, especially when you have wrapper utilities sitting outside the test.ps1 that is controlling the launch.

Anyway, that works, thanks for the advice.