Use PowerShell to remove home directories for users who no longer exist in AD

Today I had to migrate a home directory share to another server. I didn’t want to migrate folders for users who no longer existed in AD or were disabled, so I wrote a script to move those users’ folders into another location.

You could tweak this to be run as a scheduled task, thereby keeping your user home directory share clear of old users’ folders.

Note that this requires the ActiveDirectory PowerShell module in order to enumerate the list of users from AD. I started looking at a fallback method using [adsisearcher], but it wasn’t worth my time.

$homeDriveRoot = "\server1userfolders"
$leaversRoot = "\server1userfoldersoldusers"

# Get the list of folders in the home drive share
$folders = Get-ChildItem $homeDriveRoot | Select -ExpandProperty Name

# Get the list of active users from AD
$activeUsers =  Get-ADUser -Filter {Enabled -eq $true} | Select -ExpandProperty SamAccountName

# Compare the list of users to the list of folders
$differences = Compare-Object -ReferenceObject $activeUsers -DifferenceObject $folders | ? {$_.SideIndicator -eq "=>"} | Select -ExpandProperty InputObject

# For each folder that shouldn't exist, move it
$differences | ForEach-Object {Move-Item -Path "$homeDriveRoot$_" -Destination "$leaversRoot$_" -Force}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s