PowerShell find space used by inactive User Drives
Trying to figure out how to clean up our network shares brought me to a bunch of old Home Drives, and PowerShell to figure out how much we were wasting.
Like many places, my job has been very lax at cleaning up employee Home Drives once the employee has left the organization. We were running very low on space on our network shares, so I wanted to identify easy to purge folders. The following script assumes that the user folder matches the user's SAMAccountName and will go through your main users folder, check to see if there is an enabled AD account with that name, and if not add it to a list of orphaned home drives.
The second ForEach loop goes through all orphaned drives and gives a total of the space that could be reclaimed by removing them. Deleting the actual drives can be done with the following if you're feeling brave:
$OrphanedHomeDrives | % {Remove-Item $_ -Recurse -Confirm:$False}
Full script is:
$WastedSpace = 0
$InactiveUsers = @()
$OrphanedHomeDrives = @()
$ActiveUsers = @()
$USERSDIRECTORY = "FILESERVER\Users"
$UserDrives = Get-ChildItem -Directory \\$USERSDIRECTORY
ForEach ($Directory in $UserDrives){
try {
if ($InActiveUser = (Get-ADUser $Directory.Name -EA Stop).Enabled){
$ActiveUsers += $Directory.Name
}else {
$InactiveUsers += $Directory.Name
$OrphanedHomeDrives += $Directory.FullName
}
}catch{
$InactiveUsers += $Directory.Name
$OrphanedHomeDrives += $Directory.FullName
}
}
ForEach ($HomeDrive in $OrphanedHomeDrives){
$WastedSpace += ((Get-ChildItem $HomeDrive -Recurse | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum / 1GB)
}