0

I need to make a script that can delete unused windows profile folders.

I have a problem with getting permission to delete windows profile folders with PowerShell. Getting ownership with takeown.exe works fine since I can see I get the ownership of the folder including its subfolders and files. The problem comes when I have to set the permissions(FullControl). It seems like the folder and its subfolders get the correct permissions, but the files don't, which obviously result in an error when I try to delete the folder.

I have tried to solve this by using takeown.exe and icacls together, and when that didn't get me anywhere I tried using takeown.exe with Set-Acl.

This code is when I tried using takeown.exe and icacls:

$folderPath = "\\profileserver\ProfileWin8\ro1.V2"

# Take ownership and set permissions
function takeOwnership($path) {
    takeown.exe /F $path /A /r /d Y
    icacls $path /grant administrators:F /q /c /t /inheritance:e 
}

#Delete folder
function deleteFolder($path) { 
    Remove-Item $path -Force -Recurse -ErrorAction SilentlyContinue -Confirm:$false
}

takeOwnership($folderPath)
deleteFolder($folderPath)

Then I tried with Set-Acl which doesnt work either. I have to use takeown.exe for the folder since I don't have ownership and therefore wouldn't get the ACL object otherwise. I don't know if there is another way to get the ACL object without using takeown.exe:

$folderPath = "\\profileserver\ProfileWin8\ro1.V2"

takeown.exe /F $folderPath /R /D Y

$acl = Get-Acl -Path $folderPath

$acl.Access | Write-Output

$colRights = [System.Security.AccessControl.FileSystemRights]"FullControl" 
$permission = "DOMAIN\user", $colRights, "ContainerInherit,ObjectInherit", "None", "Allow" 
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission  
$acl.AddAccessRule($accessRule)

$acl.SetAccessRuleProtection($false, $false)

$acl | Set-Acl $folderPath

Remove-Item $folderPath -Force -Recurse

I am still unsure which technique I should move forward with.

4

1 回答 1

1

AFAIK icacls doesn't have a parameter /inheritance. You specify inheritance settings along with the permissions:

icacls $path /grant 'administrators:(OI)(CI)F' /t /c /q

Note that you need quotes around the user/permissions argument, so that PowerShell doesn't evaluate the parentheses as grouping expressions.

I would probably also reset the permissions on the child objects, to be on the safe side:

icacls "$path\*" /reset /t /c /q

For simplicity reasons I'd stick with takeown and icacls for this. You could do both with PowerShell, but it'd be significantly more code.

于 2018-04-12T09:08:09.177 回答