使用 PowerShell 2.0 计算 XML 属性的总和值
我有一个包含 XML 文件的目录。我很快就想浏览它们并总结存储在一个属性中的值。我已经弄清楚如何查找我感兴趣的节点。
例如:
(Select-Xml -Path .\*.xml -XPath "//*[@Attribue = 'valueImlookingfor']").Count
此命令给出当前目录中所有 XML 文件中的元素计数,这些文件在“属性”中具有值“valueImlookingfor”。
我想总结“属性”的所有值,而不是计算它们。在 PowerShell 中执行此操作的最佳方法是什么?我是 PowerShell 新手,所以这可能是微不足道的,但对我来说是未知的......
非常感谢所有提示:-)
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 :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
细分:
$total = 0
——我们将求和到这个变量中。select-xml -path .\*.xml -xpath ...
-- 返回与当前文件夹中任何 *.xml 文件中给定 XPath 表达式匹配的所有 XML 节点的集合。//*/@Attribute
-- 返回 XML 树中任意元素中的所有 attribute 节点。select-xml
返回的集合传递('pipe')到foreach
cmdlet。foreach
对集合中的每个元素执行给定的代码段。通过$_
访问集合元素。$total += [int] $_.node.value
-- 将当前属性的值添加到$total
中,该值从字符串转换为整数。$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 byselect-xml
to theforeach
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.