I’m attempting to remove a local user from a computer (named Deltagare). I need to remove both the account and the files associated with the account inside C:/Users/username
. I have issues with getting access denied event when running the script as administrator. The script is run on an administrator account. I have tried to transfer ownership, both by using takeown
, icacls
and Set-Acl
but I still get access denied at Remove-Item
Remove-LocalUser -Name "Deltagare"
# Grant ownership here using takeown, icacls or Set-Acl
Remove-Item -Path "\\?\C:\Users\Deltagare" -Recurse
How do I delete this folder using Powershell? Any ideas on how to take ownership or do I need to remove the user another way?
This is easiest with CIM/WMI, in my opinion. You'll probably want to remove it before removing the user account, however.
Get-CimInstance -ClassName Win32_UserProfile |
Where-Object { $_.LocalPath.EndsWith($UserName) } |
Remove-CimInstance -WhatIf
Remove the -Whatif
parameter to actually remove the profile, of course.
Filtering by the SID is probably even better than filtering by the username in th local path.