I ran into an challenge where there were tons of home folders for users that may or may not be active. The folders were named according to the User ID used to login to user workstations. In Active Directory, this was known as SamAccountName.
Going through Active Directory to find each user’s SamAccountName and then see if there’s a corresponding home drive folder would be tedious at best. So, there must be a better way!
Here’s a script that will iterate through all the user folders in the “E:\User” folder and then remove deactivated user folders to the “E:\DeletedHomeDirectories” folder to be dealt with later.
<# RemoveFoldersWithoutUsers.ps1 By Frank Contreras Use at your own risk #> $folders = Get-ChildItem "G:\UserShare\" foreach ($folder in $folders) { $ADUser = Get-ADUser -Filter {Enabled -eq $true -and SamAccountName -eq $folder.Name} if ($ADUser -eq $null) { "Removing " + $folder $source = "G:\UserShare\"+$folder $destination = "E:\DeletedHomeDirectories\" + $folder.Name Move-Item -Path $source -Destination $destination } }