IronManUTF8
IronManUTF8

Reputation: 57

PowerShell Error handling : how to resolve if error occurs in first or middle of the script?

I am calling a bat file in my PowerShell and given a condition in PowerShell that if it fails it should display a message "failed" and if it pass it will display a message "passed".My bat file contains unit test cases , so if all test cases pass I am getting a message in powershell "Passed" and if all test cases fail or the last test case fail in bat file I am getting a message "failed" but I am not getting display message "failed" if my first test So If first test "failed" and and second test "passed" instead of getting failure message I am getting passed message. I have used a condition $LASTEXITCODE which will give a last status of test (pass/fail) status. Is there any way to resolve this.It will be very useful.

demo.bat

@echo off
echo "running  test cases"
call npm run test folder1/file1/validate.test.js
call npm run test folder1/file2/validate.test.js

test.ps1

Write-Output "starting script......"
        .\demo.bat
    if ($LASTEXITCODE -gt 0) { 
        Write-Output "Failed"
    }
    else {    
        Write-Output "Passed"
    } 

Upvotes: 0

Views: 448

Answers (2)

JosefZ
JosefZ

Reputation: 30153

The following code snippet should return count of failed partial tests:

@echo off
set "scriptError=0" 
echo "running  test cases"
call npm run test folder1/file1/validate.test.js
if errorlevel 1 set /a scriptError+=1
call npm run test folder1/file2/validate.test.js
if errorlevel 1 set /a scriptError+=1
exit /B %scriptError%

However, you could construct the scriptError variable as binary so that it show which partial test had failed and not only count… (Hint: add 1 if 1st test fails, add 2 for 2nd test, add 4 for 3rd test, … add 2^(n-1) if n-th test fails.)

Upvotes: 1

wasif
wasif

Reputation: 15488

Unfortunately, $LASTEXITCODE will return the error code on executing whole script. It is overwritten several times. So there is no way to handle it from powershell. You have to change your batch file like this:

@echo off
echo "running  test cases"
call npm run test folder1/file1/validate.test.js
if %errorlevel% gtr 0 (echo Failed) else (echo Passed)
call npm run test folder1/file2/validate.test.js
if %errorlevel% gtr 0 (echo Failed) else (echo Passed)

Invoke this from powershell, you can get the rest cases output.

Upvotes: 1

Related Questions