Search code examples
bashpowershellreturn-value

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?


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)