Home > Back-end >  Summing command return codes
Summing command return codes

Time:07-15

I have the following powershell script that runs our unit tests:

Get-ChildItem -Path . -Recurse -Include *.Tests.csproj |
%{dotnet test $PSItem.FullName}

However, since we started using a for loop, it no longer returns a non zero value on a failed test. I still want to run everything, even if one of the tests fails. So I want to add all return codes together and return that value to indicate an error.

How can I update this powershell script to return the sum of all return values?

Edit1: This script is part of a larger CI system, so a preferred solution should only add what was requested and nothing more.

CodePudding user response:

I assume that by return code you mean process exit codes.

PowerShell reflects the exit code of the most recently executed external program (such as dotnet in this case) in the automatic $LASTEXITCODE variable:

$sumOfExitCodes = 0
Get-ChildItem -Path . -Recurse -Include *.Tests.csproj |
  ForEach-Object {
    dotnet test $PSItem.FullName
    $sumOfExitCodes  = $LASTEXITCODE
  }

# Report the sum of all exit codes as this script's exit code
exit $sumOfExitCodes

CodePudding user response:

I think I would store the result for every single project test in an object and summarize that later on.
By doing that you will also have the chance to see in detail which project failed the test and which project succeeded.

Something like this (untested)

$result = (Get-ChildItem -Path . -Recurse -Filter '*.Tests.csproj').FullName | ForEach-Object {
    [PsCustomObject]@{
        ProjectFile = $_
        TestResult  = [int](dotnet test $_)
    }
}

# show the full list
# $result | Format-Table -AutoSize

# save as csv file if you like
# $result | Export-Csv -Path ('X:\Somewhere\ProjectsTest_{0:yyyy-MM-dd}.csv' -f (Get-Date))

# show summarized result
$sum = ($result.TestResult | Measure-Object -Sum).Sum
# Write-Host "Overall result: $sum for $(@($result).Count) projects"

exit $sum
  • Related