PowerShell XML - Newbie head start required

Tagged: 

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of PB PB 8 months, 1 week ago.

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #34089
    Profile photo of PB
    PB
    Participant

    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

    #34090
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

    #34092
    Profile photo of PB
    PB
    Participant

    Trying gist now..

    #34094
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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. 🙂

    #34102
    Profile photo of PB
    PB
    Participant

    Awesome. Thank you.

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

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.