Follow up to this question: How to get a value in a foreach loop into a sum?
I have this snippet of Powershell code:
$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"
I need a way to deal with the script not erroring out if the user's homedirectory is NULL in this AD attribute.
I thought it would be an embedded IF statement below the foreach, but I can't get the If statement work properly, I keep getting syntax errors.
Can anyone assist on what the IF statement would be to make sure the foreach code runs only if the HomeDirectory has a value?
ifblock (edit your question), it is fairly easy, you' have help very soon.()instead of curly brackets{}