I have created my first PowerShell script to mass delete user profiles, For the most part it works fine, however, it does occasionally leave behind some profiles that cannot be found in Powershell when Get-CimInstance win32_UserProfile
is run.
Even though PowerShell seemingly does not see these profiles they do get touched by the script so that their last accessed date is current, everything aside from their appdata folders are deleted, and they are still in the C:\Users
directory.
The only solution I have currently is to manually select these profiles within Users
and then delete them but I'm trying to completely automate this process. I am at a loss as to what could cause this, so any advice or guidance is greatly appreciated. Here is my code:
# Grab all the user profiles and ignore anything in our exceptions
$Profiles = Get-CimInstance Win32_UserProfile | where {((!$_.Special) -and ($_.LocalPath -ne "C:\Users\Administrator") -and ($_.LocalPath -ne "C:\Users\admin1") -and ($_.LocalPath -ne "C:\Users\admin2") -and ($_.LocalPath -ne "C:\Users\admin3") -and ($_.LocalPath -ne "C:\Users\admin4"))}
# Get the number of profiles to use in -PercentComplete
$ProfilesCount = $Profiles.Count
# This for loop iterates through profiles and deletes them as well as creates our progress bar
Function ProfilesB-Gone
{
for ($i = 1; $i -lt $ProfilesCount; $i++)
{
# Our progress bar is generated and updated
Write-Progress -Activity 'Removing Profiles' -Status "Deleted $i out of $ProfilesCount profiles" -PercentComplete (($i/$ProfilesCount) * 100)
# Here we're suppressing errors and continuing while deleting our profiles
Remove-CimInstance $Profiles[$i] -EV Err -EA SilentlyContinue
}
# Remove progress bar once complete
Write-Progress -Activity 'Removing Profiles' -Status 'Complete!' -Completed
}
# Call function
ProfilesB-Gone;
# Remove all leftover profiles that remain ocasionally due to noncritical and inconsistent bug and suppress errors. Not suppressing errors causes as many error windows to show as there were $ProfilesCount.
$Profiles | Remove-CimInstance -EV Err -EA SilentlyContinue
# Give success message to inform user of script completion
Write-Host "Profiles Deleted!"
A win10 app (MicrosoftOfficeHub) makes strange links that can't be deleted in the normal way. Using something like cmd /c rmdir /s /q c:\users\user
still works, when powershell and wmi don't. How to remove user profile completely from the Windows 10 computer?