【问题标题】:Get permission to delete windows profile folder获得删除 Windows 配置文件文件夹的权限
【发布时间】:2018-04-12 06:47:58
【问题描述】:

我需要制作一个可以删除未使用的 Windows 配置文件文件夹的脚本。

我在获取使用 PowerShell 删除 Windows 配置文件文件夹的权限时遇到问题。使用takeown.exe 获得所有权工作正常,因为我可以看到我获得了文件夹的所有权,包括其子文件夹和文件。当我必须设置权限(FullControl)时,问题就来了。似乎文件夹及其子文件夹获得了正确的权限,但文件没有,这显然会在我尝试删除文件夹时导致错误。

我试图通过同时使用takeown.exeicacls 来解决这个问题,但当我尝试使用takeown.exeSet-Acl 时,我没有任何帮助。

这段代码是我尝试使用takeown.exeicacls时的代码:

$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


    【解决方案1】:

    AFAIK icacls 没有参数 /inheritance。您可以指定继承设置以及权限:

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

    请注意,您需要在 user/permissions 参数周围加上引号,以便 PowerShell 不会将括号计算为分组表达式。

    为了安全起见,我可能还会重置子对象的权限:

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

    为了简单起见,我会坚持使用takeownicacls。您可以使用 PowerShell 来完成这两种操作,但代码量会大大增加。

    【讨论】:

    • 谢谢。在我还按照您的描述重置子对象之后它起作用了。
    猜你喜欢
    • 2012-08-29
    • 2016-01-11
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2012-07-17
    相关资源
    最近更新 更多