Delete User Profiles

This script deletes all local user profiles except for specified exclusions.

Script Content

Write-Host "WARNING! This script deletes all user profiles with a few defined exceptions.`nPress any key to continue..." -ForegroundColor Red 
$null = Read-Host
Write-Host "Are you sure you want to run this script? If YES, press any key again ..." -ForegroundColor Red 
$null = Read-Host

$excludedProfiles = @("Administrator", "Public", "AdminZ", "AdminWKS", "Matur2022", "NetworkService", "LocalService", "systemprofile", "default")

$profiles = Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -notlike "*\\*"}

foreach ($profile in $profiles) {
    $username = $profile.LocalPath.Split('\')[-1]

    if ($excludedProfiles -notcontains $username) {
        Write-Host "Removing profile: $username"
        $profile.Delete()

        $sid = $profile.SID
        $regPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$sid"
        Write-Host "Removing RegKey: $regPath"
        Remove-Item -Path $regPath -Force -Recurse
    }
}

Notes

  • Includes a safety prompt before proceeding.

  • Deletes the user profile and the related registry key.

  • Must be run with administrative privileges.