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.

Note: 2 years later and at a different employer, and I built one using [adsisearcher] to remove user profile folders (not home directories) because I wanted it to run locally on a file server without the requirement to have the AD PowerShell module installed. See the bottom of the page for that update.

$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}

2017 update: Here’s a version using ADSI instead of Active Directory PowerShell that I wrote to remove old roaming user profiles. Note that you’ll need to remove the -WhatIf from the last line to have it actually delete folders

$profilesFolder = 'D:\path\to\profiles'
$profiles = Get-ChildItem $profilesFolder

foreach ($roamingProfile in $profiles) {
 # Split on the dot, because of .V2 and .V4 folders
 $username = $roamingProfile.Name.Split('.')[0]
 
 # Find a matching user using ADSI
 $matchingUser = ([ADSISEARCHER]"samaccountname=$($username)").Findone()
 
 # Skip this folder if we DO find a matching user
 if ($matchingUser -ne $null) { continue }
 
 # Remove the folder
 $roamingProfile | Remove-Item -Recurse -Force -Verbose -WhatIf
}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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