1

I can exit a powershell application with exit code by :

exit 59

How can exit with a Custom Exit Code Description?

exit 59, "Somethings Wrong"
4
  • Why not use Write-Host followed by a exit code ? The way the code is posted in above is not correct, exit is followed by an numeric code to indicate the exit code. Commented May 30, 2017 at 17:46
  • That is what i am currently doing. I was hoping there was away to send the exit code description on exit instead of before exit Commented May 30, 2017 at 18:01
  • There's no such thing as a "custom exit code description." An exit code is an integer. Commented May 30, 2017 at 18:35
  • As long as you are consistent with your error codes you can use those as you see fit in your calling application. e.g. I used 2468 to represent when a exe was in use. Commented May 30, 2017 at 19:16

1 Answer 1

5

You can't. Inside the PowerShell environment, cmdlets can return any .Net object (strings, Exceptions, etc.) to each other, but when you exit, the PowerShell process exits, and all it can return to Windows / the calling process is an integer.

https://en.wikipedia.org/wiki/Exit_status#Windows

There's nowhere to put a custom description and no way for anything else to get a description. That's years of legacy computing and backwards compatibility constraints back to when processors were small, memory expensive, and return values were (I speculate) one processor register value, or similar.

When you are in a command prompt and run these commands:

c:\> powershell
Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.

PS C:\> exit 10

c:\> echo %ERRORLEVEL%
10

you see the PowerShell process quit with the return value of 10. But there is no %ERRORDESCRIPTION% or similar standard feature to put anything else. There's just no lower level machinery for the thing you want to do.

What you can do is write to the standard error output (stderr) using Write-Error and if a program calls your script and captures stderr output, it can read it. Or you can write an error to an event log, or to a logfile.

But any of that writing has to happen while your process is running because, well, you can't do anything after your process has quit.

Sign up to request clarification or add additional context in comments.

1 Comment

Depending on your errorpreference write-error does not terminate the execution of the script. throw should be mentioned here as well I would think. Write-Error "This";"hello" vs. throw "This";"hello"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.