Skip to content

Instantly share code, notes, and snippets.

@MyITGuy
Last active May 19, 2022 16:27
Show Gist options
  • Save MyITGuy/9470051e120ae94e2febfd2f945ccc21 to your computer and use it in GitHub Desktop.
Save MyITGuy/9470051e120ae94e2febfd2f945ccc21 to your computer and use it in GitHub Desktop.
PowerShell: Set-ExitCodeAndExit (ReturnCode)
# Sends exit code to calling shell
$host.SetShouldExit([System.Environment]::ExitCode)
function Set-ExitCodeAndExit {
[CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="None")]
PARAM(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ParameterSetName="p1")]
[int]
$ExitCode
)
Write-Verbose "Setting ExitCode to $($ExitCode) and exiting..."
# When a PowerShell script is called from a batch file or Command Prompt, this line allows a return code back to the calling shell
$host.SetShouldExit($ExitCode)
exit $ExitCode
}
@cwegener
Copy link

$host.SetShouldExit() saved my life on an ancient Win7 PS2.0 machine. A simple Exit 1 would always set the return code of powershell.exe -file to zero ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment