如何将foreach循环中的值转换为总和?

时间:2016-11-21 20:33:53

标签: powershell foreach

我在foreach循环中有一个变量,如下面的代码段所示,它以MB为单位计算用户的主文件夹大小:

$TotalColItems = @()
foreach ($user in $ListofUsers)
{
    $colItems = (Get-ChildItem $user.HomeDirectory -Recurse |
                Measure-Object -Property Length -Sum)
    Write-Host "`r`n Size of:" $user.HomeDirectory
    "{0:N2}" -f ($colItems.Sum / 1MB) + " MB"
    $Calculation = "{0:N2}" -f ($colItems.Sum / 1MB) + " MB"
    $TotalColItems += $colItems.Sum
    $user.HomeDirectory + " = " + $Calculation | Out-File $LogFileName -Append
    Remove-Item $user.HomeDirectory -Force -Recurse -ErrorAction SilentlyContinue
    Write-Host "`r`n Removed HomeDirectory: " $user.HomeDirectory
    Write-Host "`r`n Verifying you want to remove the user: " $user.Name -ForegroundColor Yellow -BackgroundColor Red
    Write-Host "`r`n"
    Remove-ADObject $user.DistinguishedName
    Write-Host $TotalColItems

但我似乎无法弄清楚如何获得所有$colItems的总值,然后我可以计算MB。

我试着把它放在循环中:

$TotalColItems += $colItems

但它会在每个循环中重置自身,因此它不会保持正在运行的附加总数。

如何在每个循环中获取$colItems变量以将其值附加到变量,以便我可以得到所有用户目录大小的总和?

3 个答案:

答案 0 :(得分:3)

示例中的$TotalColItems变量初始化为数组@()是数组子表达式运算符),因此它就像一个。将它初始化为一个数字,你会发现它按预期工作(为了自我解释而重命名为变量名):

$TotalHomeDirSizeMB = 0
foreach ($user in $ListofUsers)
{
    # Calculate sum of file sizes, grab Sum property value directly
    $HomeDirSize = (Get-ChildItem $user.HomeDirectory -Recurse | Measure-Object -Property length -sum).Sum

    # Calculate and store size in MB
    $HomeDirSizeMB = $HomeDirSize / 1MB
    # Add to cumulative size variable
    $TotalHomeDirSizeMB += $HomeDirSizeMB

    # Write results to screen + file    
    Write-Host "`r`n Size of: $($user.HomeDirectory)"
    Write-Host ("{0:N2} MB" -f $HomeDirSizeMB)
    "$($user.HomeDirectory) = $HomeDirSizeMB MB" | Out-File $LogFileName -Append

    # Remove home directory
    Remove-Item $user.HomeDirectory -Force -Recurse -ErrorAction SilentlyContinue
    Write-Host "`r`n Removed HomeDirectory: " $user.HomeDirectory

    # Wait for user to verify deletion from AD, preempt Confirmation if verified
    Write-Host "`r`n Verifying you want to remove the user: " $user.Name -ForegroundColor Yellow -BackgroundColor Red
    if((Read-Host -Prompt "y for yes") -eq 'y'){
        Remove-ADObject $user.DistinguishedName -Confirm:$false
    }
}

# Write cumulative size to screen
Write-Host "Removed $TotalHomeDirSizeMB MB"

答案 1 :(得分:1)

您可以通过几种不同的方式实现您所寻找的目标,但最简单的方法可能是在开始您的foreach循环之前将$TotalColItems声明为全局变量,然后像往常一样递增。所以只需Global:TotalColItems = 0,然后将增量器更改为Global:TotalColItems += $colItems如果这对您不起作用,您可以发布完整的foreach循环供我们查看吗?

答案 2 :(得分:-1)

$obj = New-Object PSObject {
Collection = "" 
}

$colItems = (Get-ChildItem $user.HomeDirectory -Recurse | Measure-Object -Property length -sum)
Write-Host "`r`n Size of:" $user.HomeDirectory
"{0:N2}" -f ($colItems.sum / 1MB) + " MB"
$Calculation = "{0:N2}" -f ($colItems.sum / 1MB) + " MB"

Foreach($item in $ColItems) 
{
$obj.Collection = $Item
}

没有测试过这个,但我认为它应该可行....