Reputation: 95
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)
Upvotes: 4
Views: 2654