1

I have an API that returns exit codes of script runs. I save the return object in a variable called $exitCodes.

$exitCodes

will yield an object like this:

@{success=12; error=1; warning=0; unknown=0}

My goal is to be able to tally up the values of each property of $exitCodes without doing something like this:

if ($exitCodes.success + $exitCodes.error + $exitCodes.warning + $exitCodes.unknown -gt 0)
{
    do something
}

Is there a way to get the values of each property and add them together without calling each property by name? For this example, assume that every property is going to have a value of the same type.

1 Answer 1

1

These are two ways to do it off the top of my head:

$exitCodes = @{success=12; error=1; warning=0; unknown=0}

$i = 0; $exitCodes.Values | ForEach-Object {$i += $_}; $i

($exitCodes.Values | Measure-Object -Sum).Sum

If $exitCodes is actually an object and not a hashtable (edit: looks like that actually is the case, just by how you addressed the properties), try something similar by enumerating the properties using the hidden .psobject property.

$exitCodes = [pscustomobject]@{success=12; error=1; warning=0; unknown=0}

($exitCodes.psobject.Properties.Name | ForEach-Object { $exitCodes.$_ } | Measure-Object -Sum).Sum

#or use $i += etc.

If $exitCodes has a lot of additional properties, you can also filter based on additional info returned by .psobject. Example:

($exitCodes.psobject.Properties | Where-Object {$_.MemberType -eq 'NoteProperty'}).Name
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for, the second example worked perfect. Thanks!

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.