powershellpowershell-7.4

How can I return an exit code from a PowerShell module's function without exiting the shell?


I need to run my PowerShell module's PowerShell function from a Bash shell. The PowerShell function is supposed to return an exit code for the Bash shell to evaluate.

However, when I write:

function f
{
  [CmdletBinding()]
  param
  ( [Parameter()][string]$Test
  )

  process { exit 1 }
}

… in Test.ps1, using this in a PowerShell module (Test.psm1) like this:

. .\Test.ps1

… and have it run in PowerShell like this:

Import-Module .\Test.psm1
f ''

… the PowerShell console is getting closed. This is not what I want to happen.

How can I return an exit code from PowerShell module's function without terminating the current PowerShell session?


Solution

  • Let me provide some background information, to complement your own answer:


    [1] The permitted range of integer values depends on the host platform: windows permits [int] values (signed 32-bit integers), which on Unix-like platforms you're limited to [byte] values (unsigned 8-bit integers). In cross-platform code, it is therefore best to limit exit codes to between 0 and 255, inclusively.

    [2] $? is implicitly also used with && and ||, the pipeline-chaining operators.

    [3] Strictly speaking, a script-file's execution is considered successful if it terminates with exit 0 (which is the same as just exit) or exits implicitly (even if errors occurred inside the script); only if exit is actually used is $LASTEXITCODE set; thus, $LASTEXITCODE may reflect an incidental value afterwards, such as from an earlier, unrelated external-program call, which is problematic - see GitHub issue #11712. Fortunately, however, $? is set correctly in all cases, and script-file execution therefore also works with && and ||.