3

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?

4
  • Hi, please show us your attempt with the if block (edit your question), it is fairly easy, you' have help very soon. Commented Dec 14, 2016 at 20:43
  • @sodawillow - I was doing if {$_.HomeDirectory -ne $null} but it would error out still if the attribute was blank...not sure why Commented Dec 14, 2016 at 21:02
  • 1
    You need parens () instead of curly brackets {} Commented Dec 14, 2016 at 21:17
  • doh! Thank you sir Commented Dec 14, 2016 at 21:34

3 Answers 3

4

I personally like to pre-filter, such that you do not have to evaluate during each pass using if. I find this to be more easily readable/succinct, and also keeps the code from heading towards the "pyramid of doom".

This works if all of the code within the loop is dependent only on this single attribute being set (and those without it you are uninterested in).

$FilteredListOfUsers = $ListofUsers | ?{$_.HomeDirectory -ne $null}
foreach ($user in $FilteredListOfUsers) { #do work...}

That being said, the first responder's work is equally correct.

Sign up to request clarification or add additional context in comments.

1 Comment

You should also just be able to wrap the 1st line in parenthesis instead of assigning to a variable and pipe | to for-each
2

Here:

$TotalHomeDirSizeMB = 0
foreach ($user in $ListofUsers)
{
    if ($user.HomeDirectory) {
        # 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"

Comments

2
foreach ($user in $ListofUsers)
{
    if ($user.HomeDirectory) {
        your original code
    }
}

This will check if $user.HomeDirectory is not $null

3 Comments

Hi, this will output errors if $user.HomeDirectory is $null as OP wants. You'd have to test $user.HomeDirectoryinstead.
i thought he wanted to check the response from gci
if the user's homedirectory is NULL in this AD attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.