ProfileCleanup

param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$UserDirRoot,
    [Parameter()]
    [bool]$EnableDelete = $false,
    [Parameter()]
    [int]$AgeInDays = 30
)
#how old are we looking
$limit = (Get-Date).AddDays(-$AgeInDays)
#just to keep count
$too_old = 0
$still_good = 0
$total_count = 0
$invalid_users = 0
#let's get our profile folders
$folders = get-childitem "$UserDirRoot\UserProfiles"
foreach ($folder in $folders) {
$username = $folder.name
$user = get-aduser -filter {SamAccountName -eq $username}
    $sid = ($user.sid).value
$count = $user | measure
    $delete_profile = 0
switch ($count) {
#no matching user account
0 {
Write-Host "Delete profile $username - no user account found" -ForegroundColor red
            $delete_profile = 1
            $invalid_users++
}
default {
#user account is not enabled
if ($user.enabled -eq $false) {
Write-Host "Delete profile $username - user account disabled" -ForegroundColor green
$delete_profile = 1
                $invalid_users++
}
else {
    #If the account still exists and is enabled, let's make sure it's not too old
    $path = "$UserDirRoot\UserProfiles\$username\UPM_Profile\UPMSettings.ini"
    if (test-path -path $path) {
    $time = (Get-Item $path).LastWriteTime
   if ($time -lt $limit) {
    Write-Host "Delete profile $username - too old - $time" -ForegroundColor cyan
    $delete_profile = 1
    $too_old++
    }
    else { $still_good++ }
    }
    else {
    Write-Host "Delete profile $username - no settings file!" -ForegroundColor yellow
    $delete_profile = 1
    }
}
}
}
    if ($delete_profile -eq 1 -and $EnableDelete -eq $true) {
        #Delete the user profile folder
        Remove-Item -path $folder.fullname -recurse -force
        #Delete the user data folder (redirected folders)
        Remove-Item -path "$UserDirRoot\UserData\$username" -recurse -force
    }
    $total_count++
}
Write-Host "Total Profiles: $total_count"
Write-Host "Invalid or inactive users: $invalid_users"
Write-Host "Good Profiles: $still_good"
Write-Host "Old Profiles: $too_old"
Scroll to Top