Reputation: 21
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.
Upvotes: 1
Views: 342
Reputation: 2835
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
Upvotes: 1