求和从 Powershell 得到的参数

Sum parameters got from Powershell

我正在创建一个脚本,它从一个文件中逐行汇总红色目录下每个文件的大小。

现在文件的递归搜索正在运行,我得到了源文件每一行的大小总和,但我不确定如何将所有这些值加在一起。

我现在拥有的是:

#Read each line of a file for a directory
foreach($line in Get-Content .\file.txt) {
  #Prints the current line path
  echo $line
  #Prints a count of the files under that path and a sum of all files length
  Get-ChildItem -Recurse $line | Measure-Object -Property Length -Sum
}

此脚本的输出如下所示:

T:/folder_1/folder_2/2018/12/6/A
Count    : 30
Average  :
Sum      : 522382636
Maximum  :
Minimum  :
Property : Length

T:/folder_1/folder_2/2018/12/6/B
Count    : 2
Average  :
Sum      : 2835134
Maximum  :
Minimum  :
Property : Length

如何获得每个文件夹的每个 Sum 输出的总和,即所有 .Sum 属性 值的总和?

结合notjustme and Ansgar Wiechers的建议:

Get-Content .\file.txt | ForEach-Object -ov results {
  # Calculate the total size for the path at hand, and
  # output the result as a custom object.
  [pscustomobject] @ {
    Path = $_
    Length = (Get-ChildItem -Recurse $_ | Measure-Object -Property Length -Sum).Sum
  }
} | Measure-Object -Property Length -Sum | Select-Object -ExpandProperty Sum

# Use $results to access the per-path values.

注意如何使用外部 Measure-Object 对每个路径 Measure-Object 结果的结果求和。


如果您不需要存储每个路径的结果并且只需要总和,解决方案就会变得简单得多,正如 Ansgar 观察到的:

(Get-ChildItem -LiteralPath (Get-Content .\file.txt) -Recurse |
   Measure-Object -Property Length -Sum).Sum

注意Get-Content输出的行数组是如何直接传递给-LiteralPath的,这是支持的,因为-Path-LiteralPath都定义为[string[]] (字符串数组).