跟进这个问题:How to get a value in a foreach loop into a sum?
我有这段 Powershell 代码片段:
$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 = "{0:N2}" -f ($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-Host "Removed $TotalHomeDirSizeMB MB"
我需要一种方法来处理脚本,如果用户的主目录在此 AD 属性中为 NULL,则脚本不会出错。
我以为这将是 foreach 下面嵌入的 IF 语句,但我无法使 If 语句正常工作,我不断收到语法错误。
任何人都可以帮助了解 IF 语句是什么,以确保仅当 HomeDirectory 有值时才运行 foreach 代码吗?
最佳答案
我个人喜欢预过滤,这样您就不必在每次传递期间使用if进行评估。我发现这更容易阅读/简洁,并且还可以防止代码走向“pyramid of doom ”。
如果循环中的所有代码仅依赖于所设置的单个属性(以及那些没有设置您不感兴趣的属性),则此方法有效。
$FilteredListOfUsers = $ListofUsers | ?{$_.HomeDirectory -ne $null}
foreach ($user in $FilteredListOfUsers) { #do work...}
话虽如此,第一响应者的工作同样正确。
关于powershell - 如何在powershell中忽略foreach中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41151765/