Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

powershell return value $? and custom exit code

I installed powershell on Linux-Box.
At end of my *.PS1 file I put the following code:

Exit 2222

I run my ps1 file such as:

pwsh-lts -File my.ps1 

But I can’t access to 2222. How can I access it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Bash reflects the last exist code via the $? variable.

Let’s give it a try (I’m using bash on Ubuntu on WSL2, but you’ll find the same behavior in bash on any little-endian platform):

mathias@laptop:~/test$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.2 LTS
Release:        20.04
Codename:       focal
mathias@laptop:~/test$ echo $SHELL
/bin/bash
mathias@laptop:~/test$ echo $?
0
mathias@laptop:~/test$ pwsh -Command 'exit 2222'
mathias@laptop:~/test$ echo $?
174

So $? returns a value of 174, rather than 2222 – which is exactly what you should expect!

As triplee notes, the size of the underlying value is an unsigned byte, meaning its value will be truncated to 8 bits, giving you the value 174. This can be observed if you convert both values to a binary string:

mathias@laptop:~/test$ pwsh -Command '2222,174 |% {[convert]::ToString($_, 2).PadLeft(16, "0")}'
0000100010101110
0000000010101110
#       ^^^^^^^^
# Notice how the least significant 8 bits are the same

So there’s you’re answer:

  • To read the last exit code in bash: evaluate $?
  • To avoid having the value truncated: pick an exit code < 255 (so it fits in an unsigned byte)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading