1

I'm attempting to create a PowerShell script that queries a website using an API that responds with JSON data. I then want to get the sum of two columns that are selected. I'm new to PowerShell scripting and this seems simple but I can't find the answer. Hoping someone can help.

An example of the returned JSON from the API:

{"getuserbalance":{"version":"1.0.0","runtime":4.3599605560303,"data":{"confirmed":0.05500048,"unconfirmed":0.00472891,"orphaned":0}}}

This is what I have so far:

$balance = 'www.example.com/index.php?page=api&action=getuserbalance'
Invoke-WebRequest $balance |
ConvertFrom-Json |
Select -expand getuserbalance |
select -expand data |
select confirmed, unconfirmed

Which gives me:

 confirmed unconfirmed
 --------- -----------
 0.05500048  0.00472891

Unsure about how to add these two together. I looked at the Measure-Object cmdlet but didn't see a way to sum two columns.

Your help is appreciated.

Thanks,

Dragnan

1 Answers1

1

If you want to output only the sum itself, use the ForEach-Object cmdlet:

[pscustomobject] @{ name = 'foo'; confirmed = 1; unconfirmed = 2 } | 
  ForEach-Object { $_.confirmed + $_.unconfirmed }

This yields:

3

The script block ({ ... }) passed to ForEach-Object is invoked for every input object, and automatic variable $_ inside the script block refers to the input object at hand.

To assign the result to a variable, simply place $sum = before the pipeline; with multiple input objects, $sum will receive an array of values.

Run Get-Help ForEach-Object to learn more.


If you want to add a column containing the sum, use a calculated property:

[pscustomobject] @{ name = 'foo'; confirmed = 1; unconfirmed = 2 } | 
  Select-Object confirmed, unconfirmed, @{ n='combined'; e={ $_.confirmed + $_.unconfirmed } }

This yields:

confirmed unconfirmed combined
--------- ----------- --------
        1           2        3

To learn more about calculated properties, see this answer of mine.

mklement0
  • 382,024
  • 64
  • 607
  • 775