Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

18 Oct 2011

Force the removal of a file with PowerShell

Last couple of weeks I have been generating a lot of files (and restricting their ACLs) and today I decided to remove all those files. The problem is that my user account did not have permissions on those files. Here is a small script that will first take ownership of the file, then grants FullControl permissions, and finally removes the file 🙂

function RemoveFile 
	&takeown /F $FileName
	$User = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
	$Acl = Get-Acl $FileName	  
	$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($User, "FullControl", "Allow")	  
	Set-Acl $FileName $Acl
	Remove-Item $FileName 

Get-ChildItem *.txt -R | % { RemoveFile $_.FullName; }

Edit on 2011-10-19

Resetting the permissions with icacls c:\output /reset /t and then calling Remove-Item c:\output -R does the trick.

function RemoveFiles 

	icacls $Directory /reset /t 
	Remove-Item $Directory -R 

RemoveFiles c:\output;