在压缩时计算文件夹大小之前和之后

时间:2016-11-04 16:29:56

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

我有下面的代码适用于压缩符合我的条件的文件并删除文件,但我想要添加的是它来计算前后的文件夹大小并确定差异。这种作品但不是很好。想知道是否有更好的方法。请记住,此脚本通常运行3-4天,因为它遍历的文件系统大小超过3TB。所以我希望它基本上不仅报告它清理了什么,而且报告了它回收了多少空间。

$Before = (Get-ChildItem "U:\UDS\Test" -recurse | Measure-Object -property length -sum).Sum

Function LogWrite
{
Param ([string]$logstring)

Add-content $Logfile -value $logstring
}

$PathToZipper="C:\Program Files\7-Zip"
$UDSFilesFolder="U:\UDS\Test"
$FileMask="*.sas7bdat"
$TimeBound="12/31/2015"
dir $UDSFilesFolder -Recurse -Filter $FileMask|where{$_.LastWriteTime -lt  $TimeBound}|foreach{
$PathToFile=Split-Path $_.FullName
$PrevSize=(Get-ChildItem $pwd.path | Measure-Object -property length -sum).Sum
$ZipProcess=Start-Process "$PathToZipper\7z.exe"  -ArgumentList " a -tzip `"$PathToFile\$($_.BaseName).zip`" `"$($_.FullName)`"" -Wait -PassThru
if (!$ZipProcess.ExitCode) {
    del $_.FullName
    LogWrite $_.FullName
}
    $AfterSize=(Get-ChildItem $pwd.path | Measure-Object -property length -sum).Sum
    $Diff = "{0:N2}" -f (($PrevSize-$AfterSize)/1MB)
    LogWrite $PrevSize, $AfterSize, $Diff
}

$After = (Get-ChildItem "U:\UDS\Test" -recurse | Measure-Object -property length -sum).Sum
$Calc = "{0:N2}" -f (($Before-$After)/1MB)

# *********************************************************************************************************** 
#   Now lets cleanup LogFiles older than 30 days
# *********************************************************************************************************** 

Get-ChildItem *.log | where {$_.LastWriteTime -le (Get-Date).AddDays(-30)} | remove-item -verbose


$smtpServer = "mailserver"
$smtpFrom = "from"
$smtpTo = "to"
$messageSubject = "Sample File Maintenance Script Task Completed (UDS)"
$messageBody = @"
This email is to inform you that the regularly scheduled tmp file maintenance script task completed successfully on DTWFP3.  

The script cleared up an extra $Calc MB of disk space.

Current folder size is: $($colItems = (Get-ChildItem "U:\UDS\Test" -recurse | Measure-Object -property length -sum)
"{0:N2}" -f ($colItems.sum / 1MB) + " MB")
"@


$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)

1 个答案:

答案 0 :(得分:0)

无视,我能够通过创建一个空数组并将我的计算写入foreach循环中的数组然后将数组值一起添加来解决这个问题。像魅力一样工作