Lazy remove pesky files on Windows 
            
                        There are some files on Windows which cannot be trivially removed, even if you are a full Administrator.
This PowerShell script makes sure that you remove them nonetheless.
Tested on Windows 10 x64.
Note: this script does not remove the files that are opened by a Windows process or if the file paths are more than 255 characters.
#ps1
# Run this as administrator
# !!! Make sure you read this script ten times before executing it
$dirToRemove = "C:\PeskyFolder"
takeown.exe /F "${dirToRemove}" /R
if ($LASTEXITCODE) {
    Write-Host "Failed to take ownership of ${dirToRemove}"
    exit 1
}
Write-Host "Took ownership of ${dirToRemove}"
icacls.exe "${dirToRemove}" /GRANT "Administrators:F" /T
if ($LASTEXITCODE) {
    Write-Host "Failed to grant full admin rights to ${dirToRemove}"
    exit 1
}
Write-Host "Granted full admin rights to ${dirToRemove}"
$rmCmd = 'rmdir /s /q "' + $dirToRemove + '"'
cmd /c "${rmCmd}"
if ($LASTEXITCODE) {
    Write-Host "Failed to remove ${dirToRemove}"
    exit 1
}
Write-Host "${dirToRemove} has been removed"
                    
                    That's all, folks!
Tweet