My xml is something like this
<parent>
<somethingIamNotInterestedin>
....
</somethingIamNotInterestedin>
<body>
<event>
<eventid>1234</eventid>
<list>
<item>some text</item>
<item>some text</item>
<item>some text</item>
...many more
</list>
<action>DELETE</action>
</event>
<event>
<eventid>3456</eventid>
<list>
<item>some text</item>
<item>some text</item>
<item>some text</item>
...many more
</list>
<action>ADD</action>
<event>
<body>
</parent>
I managed to count all the items in the file, but i'd like to have it grouped by event. something like (assuming i have 245 in the first list and 123 in the second)
1234;DELETE;245
3456;ADD;123
I did something like this
$events=$xml.parent.body.SelectNodes('Event')
foreach ($event in $events) { write-host $event.list.SelectNodes('item').count}
but i always get the total number.
I suggest relying exclusively on PowerShell's adaptation of the XML DOM (accessing elements as if they were properties) and using Select-Object
with a calculated property to add the item count:
$xml.parent.body.event |
Select-Object eventid,
action,
@{ Name='count'; Expression={ $_.list.item.Count } }
Output, with your (corrected) sample data:
eventid action count
------- ------ -----
1234 DELETE 3
3456 ADD 3
The above outputs [pscustomobject]
instances.
To get the exact string output as in your question, you can pipe to
ConvertTo-Csv -Delimiter ';' -NoHeader -UseQuotes AsNeeded
in PowerShell (Core) 7; in Windows PowerShell, a bit more work is needed.