views:

52

answers:

1

I have a directory with XML files. I quickly want to go through them and sum upp the value stored in one attribute. I have figured out how to fidn the nodes I am interested in.

For example:

(Select-Xml -Path .\*.xml -XPath "//*[@Attribue = 'valueImlookingfor']").Count

This command gives me the count of elements in all of the XML files in the current directory which has the value "valueImlookingfor" in the "Attribue".

I want to sum up all the values of the "Attribute", not count them. What would be the best way to do this in PowerShell? I am new to PowerShell so this may be trivial but un-known to me...

All tips are much appreciated :-)

+1  A: 
$total = 0; select-xml -path .\*.xml -xpath "//*/@Attribute" | foreach { $total += [int] $_.node.value }; $total

Breakdown:

  • $total = 0 -- we're going to sum into this variable.
  • select-xml -path .\*.xml -xpath ... -- return a collection of all the XML nodes matching the given XPath expression in any of the *.xml files in the current folder.
  • //*/@Attribute -- return all the attribute nodes in any element, anywhere in the XML tree.
  • | foreach { ... } -- pass ('pipe') the collection returned by select-xml to the foreach cmdlet. foreach executes a given code segment on each element in the collection. The collection element is accessed via $_.
  • $total += [int] $_.node.value -- add to $total the value of the current attribute, converted from a string to an integer.
  • ; $total -- finally, return the value of $total. As this isn't assigned anywhere, the value is written to the console.
Oren Trutner
Thanks! I'm not all familiar with PowerShell yet... much appreciated!
Yooakim