Author Posts

January 20, 2016 at 7:24 am

Clarification of approach required for reading XML data in PowerShell.

First typeset the XML file:
[xml]$mydatalist = (get-content c:\mydatalist.xml)
That piece I'm OK with!!!

The content of this file is noted below and for each entry that has 0 in I want to export the data for and and total each of them i.e. a total of SomeData1, a total of SomeData2 and a total of SomeData3 — all where SomeData4=0.

What can I do in PowerShell to achieve this?

File content here:

Thanks,
PB

January 20, 2016 at 7:26 am

The forum software isn't very friendly to posting XML (which looks like HTML tags). Can you put it on a gist instead?

January 20, 2016 at 8:08 am

Trying gist now..

January 20, 2016 at 8:58 am

You can use Where-Object and Measure-Object to get that information:

$mydatalist.MyDataList.MyData |
Where-Object { $_.SomeData4 -eq 0 } |
Measure-Object -Sum -Property SomeData1,SomeData2,SomeData3

With that command you would get 3 objects, one for each property name. Each object would have a Sum property. If you wanted a single object, you could do something like this to convert it:

$sums = $mydatalist.MyDataList.MyData |
        Where-Object { $_.SomeData4 -eq 0 } |
        Measure-Object -Sum -Property SomeData1,SomeData2,SomeData3

[pscustomobject] @{
    SomeData1Sum = $sums | Where-Object { $_.Property -eq 'SomeData1' } | Select-Object -ExpandProperty Sum
    SomeData2Sum = $sums | Where-Object { $_.Property -eq 'SomeData2' } | Select-Object -ExpandProperty Sum
    SomeData3Sum = $sums | Where-Object { $_.Property -eq 'SomeData3' } | Select-Object -ExpandProperty Sum
}

Or, if you prefer, use your own loop and total the properties up:

$totalOne = $totalTwo = $totalThree = 0

foreach ($object in $mydatalist.MyDataList.MyData)
{
    if ($object.SomeData4 -ne 0) { continue }

    $totalOne += $object.SomeData1
    $totalTwo += $object.SomeData2
    $totalThree += $object.SomeData3
}

[pscustomobject] @{
    SomeData1Sum = $totalOne
    SomeData2Sum = $totalTwo
    SomeData3Sum = $totalThree
}

Many ways to skin a cat. 🙂

January 20, 2016 at 11:59 am

Awesome. Thank you.

And if I wanted to pipe this info to a CSV file as well as to the CLI?