You can try the following (for profiles that haven't been updated in 6 months):
# Define the threshold date (6 months ago)
$thresholdDate = (Get-Date).AddMonths(-6)
# Get a list of user profiles excluding the Administrator profile
$userProfiles = Get-CimInstance Win32_UserProfile | Where-Object { $_.Special -ne $true -and $_.LocalPath -notlike "*\\Administrator" } | Select-Object LocalPath, SID, LastUseTime
# Filter profiles that haven't been updated in the last 6 months
$profilesToDelete = $userProfiles | Where-Object { $_.LastUseTime -lt $thresholdDate }
# Delete the identified profiles
foreach ($profile in $profilesToDelete) {
Write-Host "Deleting profile: $($profile.LocalPath)"
Remove-CimInstance -ClassName Win32_UserProfile -Filter "SID='$($profile.SID)'"
}
Save this script as a .ps1 file, such as DeleteOldUserProfiles.ps1
. Then, you can run this script periodically using Task Scheduler or another automation tool to automate the process.
Make sure to test the script in a safe environment before deploying it to production. Additionally, ensure that you run the script with administrative privileges to delete user profiles successfully.
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin