Forum Discussion
UserProfile Management with PowerShell
$ErrorActionPreference = "SilentlyContinue"
$Path = "C:\Users"
$UserFolders = Get-ChildItem -Path $Path -Directory
$currentDate = Get-Date
$ageLimit = 60
# Set the execution policy to bypass (use with caution in production)
Set-ExecutionPolicy Bypass -Force
# Loop through each user profile folder
ForEach ($UserFolder in $UserFolders) {
$UserName = $UserFolder.Name
# Only process profiles that have an NTUser.dat file
$NTUserPath = "$Path\$UserName\NTUSER.DAT"
If (Test-Path $NTUserPath) {
$Dat = Get-Item $NTUserPath -Force
$DatTime = $Dat.LastWriteTime
# Reset NTUSER.DAT's LastWriteTime to match the folder's LastWriteTime
If ($UserFolder.Name -ne "default") {
$Dat.LastWriteTime = $UserFolder.LastWriteTime
}
}
# Calculate profile age and delete if older than $ageLimit
$profileAge = ($currentDate - $UserFolder.LastWriteTime).Days
If ($profileAge -ge $ageLimit) {
# Remove user profile and any content inside it (use with caution)
Try {
Remove-Item -Path $UserFolder.FullName -Recurse -Force
Write-Host "Deleted profile: $UserName"
} Catch {
Write-Host "Error deleting profile: $UserName - $_"
}
}
}
# Optional: Clean up empty folders (if necessary)
$EmptyFolders = Get-ChildItem -Path $Path -Directory | Where-Object { $_.GetFileSystemInfos().Count -eq 0 }
ForEach ($EmptyFolder in $EmptyFolders) {
Try {
Remove-Item -Path $EmptyFolder.FullName -Force
Write-Host "Deleted empty folder: $($EmptyFolder.Name)"
} Catch {
Write-Host "Error deleting empty folder: $($EmptyFolder.Name) - $_"
}
}
Write-Host "Profile cleanup complete."
Hey! Thanks for that script and explanation! Is it possible (and how) to exclude profiles from being deleted, like system defaults and post-created admin accounts? Do the cleaning operation also delete profile registry data?