2

I have the function below where i pass in two arrays. I would like the script to exit on the first occurrence of an error. I tried different variations but i can't make the script to stop early.

I have tried to use ($LastExitCode -eq 0) it doesn't seem to work, all the scripts still continue running.

I also tried If ($? -ne "True") it doesn't work either, all the tests don't run at all.

function Run-Coverage {

    param($openCoverPath,$testExecutorPath,$dllPath,$output)

& $openCoverPath `
-threshold:100 `
-register:user `
-target:$testExecutorPath `
-targetargs:"$dllPath" `
-output:$output `

}

function Run-Tests
{
    param($Dll,$Xmls)

    for ($i=0; $i -lt $Dlls.length; $i++) 
    {
        $TestParam = $Dlls[$i]
        $resultParam = $Xmls[$i]
        $dllPath = -join("`"",$projectBasePath,$TestParam," ","/TestCaseFilter:`"(TestCategory!=RequiresData)`"","`"")
        $output = -join($outputPath,$resultParam)

        try
        {
            Run-Coverage -openCoverPath $openCoverPath -testExecutorPath $testExecutorPath -dllPath $dllPath -output $output
        }
        catch
        {            
            Write-Host "Exiting loop"
            break
        }
    }
}

2 Answers 2

3

If you add [CmdletBinding()] as the first line inside the function (above the param() block), you can call the function with added Common parameters like ErrorAction, ErrorVariable etc.

try {
    Run-Coverage -openCoverPath $openCoverPath -testExecutorPath $testExecutorPath -dllPath $dllPath -output $output -ErrorAction Stop
}
catch {
    throw
}
Sign up to request clarification or add additional context in comments.

Comments

1

As @Paolo answered - you can do it easily using $ErrorActionPreference = "Stop" or make it a little bit custom using:

trap {
    Write-Host "Exception occured: $($_.Exception.Message)";
    #Some action to do with the error
    exit 1;
}

Comments

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.