Home > Mobile >  Execute the other powershell script if the previous one is successful only
Execute the other powershell script if the previous one is successful only

Time:05-21

I know this sounds very common but still even searching not able to find soltion for my use case. What i a trying to do is i am calling one powershell after another from one file say "Test" and scripts Script A and Script B

......
ScriptA.ps1
ScriptB.ps1
.....other stuff

Now if my scriptA gets executed successfully then ScriptB should execute but if ScriptA throws any exception for which i have already put try/catch block inside ScriptA, ScriptB should not execute. But i am not able to enforce any check from my "Test" to stop execution of ScriptB.ps1.

Looked for the exit codes but not sure how to collect back in the "Test" something like

......
ScriptA.ps1----returns exit code 1
if(exit code!=1)
{
  ScriptB.ps1
}
else
{
  "Cant execute due to error"
}
.....other stuff

CodePudding user response:

Use a loop statement (like foreach($thing in $collection){...}) to invoke each script in succession, then break out of the loop on failure - which you can assess by inspecting the $? automatic variable:

$failed = $false
foreach($scriptFile in Get-ChildItem -Filter Script*.ps1){
    & $scriptFile.FullName
    if(-not $?){
      $failed = $true
      break
    }
}

if($failed){
    # handle failure (exit/return or whatever is appropriate)
} else {
    # success, continue here
}

CodePudding user response:

If your .ps1 scripts communicate failure by nonzero exit code - via an exit statement - you must use the automatic $LASTEXITCODE variable to check for such an exit code:

.\ScriptA.ps1
if ($LASTEXITCODE -eq 0) {
  .\ScriptB.ps1
}
# ...

In PowerShell (Core) 7 , you can more simply use &&, the pipeline-chain AND operator:

# PowerShell 7  only.
.\ScriptA.ps1 && .\ScriptB.ps1  # Execute ScriptB only if ScriptA succeeded.
  • Related