Why does my VSTS custom task passes with exit code 1?

Viewed 7019

I've the following annoying problem. My custom VSTS build task won't fail. It always passes, while the $LASTEXITCODE is other then zero.

The code does as expected. It generates an error in the log. Despite that, the step succeeds and the build / release continues.

Screenshot: screenshot I've included a write-host with the exit code as well which shows exitcode 1 as well.

Code:

Try {
    ....
    #Loop through the server list
    Foreach ($Server in $machines) 
    {
        # Use SSL or not    
        If($UseSSL -eq $true) 
        {
            Write-Host "Connecting to $Server using a SSL connection (TCP/5986), Skip CA Check: $CheckCA ..."
            $s = New-PSSession -ComputerName $Server -Credential $Cred -UseSSL -SessionOption $SessionOptions
        }
        Else
        {
            Write-Host "Connecting to $Server with an unsecure connection (TCP/5985) ..."
            $s = New-PSSession -ComputerName $Server -Credential $Cred
        }

        # Run
        $ExitCode = Invoke-Command -Session $s -ScriptBlock $script -ArgumentList $ApplicationPoolName,$Action,$Killswitch

        # Cleanup the session
        Write-Host "Closing connection to $Server."
        Remove-PSSession -Session $s
    }
} Catch {
    Write-Host "##vso[task.logissue type=Error;]$Error"
    $ExitCode = 1
} Finally {
    #Leave TFS/VSTS trace
    if (Get-Command -Name Trace-VstsEnteringInvocation -ErrorAction SilentlyContinue) {
        Trace-VstsLeavingInvocation $MyInvocation
    }
    write-host "ExitCode: $ExitCode"
    Exit $ExitCode
}

What am i missing here?

2 Answers

I solved it by removing the finally part.

Not working:

try {
    .... do stuff ....
} catch {
   write-error "some error"
   exit 1
} Finally {
  .. some final steps ...
}

Working:

try {
    .... do stuff ....
} catch {
   write-error "some error"
   exit 1
} 

For people arriving here, having the same problem with BAT/CMD files, my solution was to add this line:

exit /b %ERRORLEVEL%

to force transmitting the errorlevel to VSTS/TFS Command-Line Task

Related