使用PowerShell对文本求值

时间:2012-10-01 21:14:30

标签: powershell powershell-v2.0

我有这个ps代码

PS > Select-String -path .\build-count-warn.txt -pattern "[1-9]?[0-9]+ warn"

warn.txt:1:    0 Warning(s)
warn.txt:2:    1 Warning(s)
warn.txt:3:    2 Warning(s)

...

那么如何扩展ps脚本并报告0 + 1 + 2 = 3

的总和

2 个答案:

答案 0 :(得分:5)

捕获正则表达式中的数值,如下所示:

PS> "0 warnings","1 warnings","5 warnings" | Select-String "(\d+) warnings" | 
        Foreach {$_.Matches.Groups[1].Value} | Measure -Sum


Count    : 3
Average  :
Sum      : 6
Maximum  :
Minimum  :
Property :

仅供参考我在支持成员枚举的PowerShell V3上进行了测试。在V2上,您可能需要这样做:

PS> "0 warnings","1 warnings","5 warnings" | Select-String "(\d+) warnings" | 
        Foreach {$_.Matches | Foreach {$_.Groups[1].Value}} | Measure -Sum

答案 1 :(得分:2)

你可以更快地尝试这个:

  PS II>  $s="0 warnings","1 warnings","5 warnings" 
  PS II>  [regex]::matches($s,"(\d+)\s*warnings") | measure -inp {$_.Groups[1].Value} -sum