Reputation: 1575
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
}
}
}
Upvotes: 2
Views: 1789
Reputation: 61028
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
}
Upvotes: 3
Reputation: 938
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;
}
Upvotes: 1