【发布时间】:2018-04-12 06:47:58
【问题描述】:
我需要制作一个可以删除未使用的 Windows 配置文件文件夹的脚本。
我在获取使用 PowerShell 删除 Windows 配置文件文件夹的权限时遇到问题。使用takeown.exe 获得所有权工作正常,因为我可以看到我获得了文件夹的所有权,包括其子文件夹和文件。当我必须设置权限(FullControl)时,问题就来了。似乎文件夹及其子文件夹获得了正确的权限,但文件没有,这显然会在我尝试删除文件夹时导致错误。
我试图通过同时使用takeown.exe 和icacls 来解决这个问题,但当我尝试使用takeown.exe 和Set-Acl 时,我没有任何帮助。
这段代码是我尝试使用takeown.exe和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)
然后我尝试了Set-Acl,它也不起作用。我必须对文件夹使用takeown.exe,因为我没有所有权,因此不会获得 ACL 对象。不知道有没有其他方法可以不使用takeown.exe获取ACL对象:
$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
我仍然不确定应该采用哪种技术。
【问题讨论】:
标签: windows powershell filesystems acl icacls