如何使用powershell仅对第二列值求和?

时间:2013-06-26 12:08:19

标签: powershell powershell-v2.0 powershell-v3.0 powershell-v1.0

sharesize.ps1

echo " "
$date1 = Get-Date
Write-Host -foreground Yellow -background Black "Script Started at $date1"

$path = "\*"

get-childitem $path | where {$_.PSIsContainer} | foreach { 

$size = (Get-ChildItem $_ -recurse | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum 

$size = "{0:N2}" -f ($size / 1MB) + " MB"

$obj = new-object psobject 
add-member -inp $obj noteproperty Path $_.fullName 
add-member -inp $obj noteproperty "Size(MB)" $size 
[array]$report += $obj
}


#display the table
$a = "<style>"
$a = $a + "BODY{background-color:green;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 2px;padding: 0px;border-style: solid;border-color: black;background-color:Yellow; font-family: Arial; font-size: 12pt}"
$a = $a + "TD{border-width: 2px;padding: 2px 6px 2px 3px;border-style: solid;border-color: black;background-color:Azure; font-family: Arial; font-size: 10pt}"
$a = $a + "</style>"


$report | Sort 'Size' -Descending | ConvertTo-HTML -head $a -title "Process Information" -body "<H2>Service Information</H2>"| Out-File -Append c:\temp\folder.html


$date2 = Get-Date
echo " "
Write-Host -foreground Yellow -background Black "Script Ended at $date2"
echo " "

以上代码对我很有帮助,非常感谢以下帮助。

这里我的要求是添加第二列的总和并将输出附加到上面的代码输出html(c:\ temp \ folder.html)的最后一行,作为,


       Path                   | Size(MB)

 C:\NVIDIA\Displaydriver      |  400 MB
  *                           |  860 MB
  *                           |  100 MB
  *                           |   * MB
  *                           |   * MB

       Total                  |  1000 MB(sum of all numbers in 2nd column values)

我还需要将第二列值和总行对齐到CENTER。

请帮助

3 个答案:

答案 0 :(得分:8)

总结大小,请执行以下操作:

$totalSize = ($report | Measure-Object 'Size(MB)' -Sum).Sum

答案 1 :(得分:0)

$total = 0 
$report | % {[float]$tmp = $_."Size(MB)".TrimEnd(" MB"); $total += $tmp}

然后,您可以在转换To-html和bango之前将$total对象添加到自定义$report对象。谢谢你的整洁剧本。

只有让我感到困惑的是你的()你的大小属性$ report让PS认为它是一种方法,因此引用。这不是最好的惯例,但它确实有效。

更明确地说:

...
[array]$report += $obj
}

$total = 0 
$report | % {[float]$tmp = $_."Size(MB)".TrimEnd(" MB"); $total += $tmp}
$obj = new-object psobject 
add-member -inp $obj noteproperty Path "Total Size: "
add-member -inp $obj noteproperty "Size(MB)" $total 
[array]$report += $obj
#display the table
...

另外,删除| Sort Size -Descending以显示总数显示在底部。

答案 2 :(得分:0)

我有类似的需求,这是我的简单解决方案:

k