Remove privileged folder in Windows 7

Ever found yourself in the situation where you wanted to delete a folder in Windows 7, but you can’t because it has special rights in some way?

An example of such a folder could be the %windir%\winsxs.

In my case I had attached a virtual disk file (.vmdk) from one virtual machine to a new virtual machine.

So I wanted to clean this disk of the unneeded Windows folder, but as this folder as well as most of the subfolders are owned by TrustedInstaller, not by the local Administrators group. For the %windir%\winsxs folder, the administrators group as well as the local system user (NT Authority\System) has only read access to the files.

In order to delete the folder you have to do two things:

  1. Take ownership of the folder and files
  2. Grant the required user at least write access to the folder and files so they can be deleted

The above can be done using the %windir%\system32\takeown.exe and the %windir%\system32\Icacls.exe

If doing this on one machine, then you could just run the respective command lines:

  • takeown.exe /F d:\windows /R /D Y
  • Icacls.exe d:\windows /grant *:(F) /T /C

But if you ever have to repeat it, then it should have been scripted:

############
#Set-RestrictedFolderRights.ps1
#Set-RestrictedFolderRights -folder
############
param([string]$Folder="")
if($Folder -eq ""){Write-Host "Please specify folder...";Break}
############
#Functions
############

Function Get-UserSID(){
	$sCurrentUser = [system.environment]::UserName
	$sCurrentUserdomain = [system.environment]::Userdomain
	$objUser = New-Object System.Security.Principal.NTAccount($sCurrentUserdomain, $sCurrentUser)
	$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
	$strSID.Value
}#end function Get-UserSID

############
#Main Script
############
$sSysFolder = ([system.environment]::SystemDirectory)
$sArgsA = '/F '+$Folder+' /A /R /D Y'

#grant ownership of the folder and all subfolders to the administrators group..
Start-Process -wait -FilePath "$sSysFolder\takeown.exe" -ArgumentList $sArgsA

#grant the logged on user full control of the folder and it's entire content
$sArgsB = $folder+' /grant *'+(Get-UserSID)+':(F) /T /C'
Start-Process -wait -FilePath "$sSysFolder\icacls.exe" -ArgumentList $sArgsB
PS > Set-RestrictedFolderRights -folder d:\Windows

After that the folder can be deleted.

A word of caution, there is no error checking in the script, so if you target the %systemroot% (usually c:\windows), the rights will be altered. As the script only adds permissions, the impact is not that huge, if the folder is not deleted after. But the rights are set in this manner for a reason

http://technet.microsoft.com/en-us/library/cc731677(WS.10).aspx

/theadminguy