The lazy programmer scripts
scripts that work

Lazy remove pesky files on Windows GitHub

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!

Written by kami on Thursday August 9, 2018
Permalink - Tags: powershell, windows, cmd

Leave a comment

comments powered by Disqus

« Lazy pro usage of bash associative arrays (dictionaries) - Lazy enable TLS 1.2 on Windows 7 / Windows 2008 R2 »