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?
6 Answers
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.
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.
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.
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!
Rebooting usually does the trick since that's how group policy handles it. It might be worth trying that if you can.
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.

Related Questions
Can't Load PhpMyadmin On After Server Update
Redirect www to non-www in Apache Conf
How To Check If Your SSL Cert Is SHA 1
Windows TrackPad Gestures