4

Powershell: While calling a subscript from a script, if the subscript is exiting with failure (i.e. exit code not 0), the main script is still exiting with exit code 0, showing as success.

Since subscript command is executed in script there is no error from main script side. How to make main script read the exit code of the subscript to show exit code as failure?

I had tried to return value before exiting from subscript and to call it in main script or using the $lastexitcode value, but those didn't worked.

Main Script:

  • AppendFile.ps1

    function ExitWithCode
    {
        param
        (
            $exitcode
        )
        $host.SetShouldExit($exitcode)
        Write-Host "($exitcode)"
        exit
    }
    #..... Do something
    
    #Calling subscript from main script
    & C:\Testappendfile.ps1
    if ($LASTEXITCODE -ne 0){
        ExitWithCode -exitcode 321
    }
    else {
        ExitWithCode -exitcode 0
    }
    
  • TestAppendFile.ps1

    function ExitWithCode
    {
        param
        (
            $exitcode
        )
        $host.SetShouldExit($exitcode)
        Write-Host "($exitcode)"
        exit
    }
    
    $FileExists = Test-Path C:\Files\check.txt
    If ($FileExists -eq $True){
        ExitWithCode -exitcode 0
    }
    else {
        ExitWithCode -exitcode 321
    }
    

If filepath is incorrect, then I am getting in output:
(321)
(0)

instead of
(321)
(321)

1
  • did you try $error[-1] to get the last error message generated in the session? Any other answer will require you to post your code. Commented Jul 13, 2015 at 4:01

1 Answer 1

1
trap { $host.SetShouldExit(-1) }
Sign up to request clarification or add additional context in comments.

1 Comment

This need to be used in child script if I'm not wrong. But i'm unable to get the result. I am already using the $host.SetShouldExit ($exitcode) in both my scripts, so my result at end of execution of main script is coming as: Exit Code 1 Exit Code 0

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.