How to Delete User Profiles with PowerShell When They're In Use?
Asked by
TechSavvyNinja42
I'm running a PowerShell script to delete specific user profiles from certain workstations using third-party software. The script looks like this:
`$PurgeUser = @("LoginID")`
`$results = Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('')[-1] -eq $purgeuser} | Remove-CimInstance`
Most of the time, it works great and removes the targeted profile. However, occasionally I get this error: **Remove-CimInstance : The process cannot access the file because it is being used by another process.** This happens even if the user hasn't logged in recently. I've noticed if I reboot and immediately run the script, the removal goes through, but that's not always feasible. Does anyone know how to release the folder so that I can delete the profile?
Answers
Make sure the user isn't still logged in. You can check with commands like `qwinsta` or `query /user` to see session status and log them off if needed.
Reply to this answer
Rebooting usually does the trick since that's how group policy handles it. It might be worth trying that if you can.
Reply to this answer
Sometimes, certain programs launched at startup access user data in the AppData directory, which can cause the profile to remain in use. Keep that in mind!
Reply to this answer
There are various reasons you can't delete a profileโlike the user being logged in, background services, or an antivirus scan in progress. Iโd suggest creating a list of profiles to delete and setting up a startup task. Also, for profiles that canโt be deleted, you can remove the profile folder manually.
Reply to this answer
I havenโt done it personally, but this is a common problem. A quick search shows a lot of discussions about it; you might find some helpful insights.
Reply to this answer
The profile won't unload if something has the user's registry hive open. Some software might be scanning the registry, leading to this error. Rebooting usually clears it up.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions