Wednesday, May 11, 2016

Find Orphaned Home Drives for Deleted AD Accounts

This script will find all home drives and for each test if the AD user still exists. If it doesn't, it will gather the folder size and output that with the user ID to a text file. Good one for general housekeeping.


#Compare all H drive folders to AD user accounts.
#If no match is found output a file with the user name and folder size in MB.
#Add all folders found and output total at the end

$HomeDriveFolders = Get-ChildItem -path "H:\Users" | select -expandproperty Name

$totalsize = 0

foreach($folder in $HomeDriveFolders)
    $user = ""
    $user = $(try {get-aduser $folder | select -ExpandProperty SAMACCOUNTNAME} catch {$null})
    if ($user -ne $folder)
        $foldersize = (Get-Item "H:\Users\$folder").GetFiles() | Measure-Object -Sum Length
        $foldersize = [math]::Round($foldersize.sum / 1MB)
        $totalsize = $totalsize + $foldersize
        "$folder,$foldersize" | out-file H:\usercomparisonexport.txt -append

"---------------------((TOTAL))",$totalsize | out-file H:\usercomparisonexport.txt -append