powershell 删除文件夹而不获取所有权?

powershell 删除文件夹而不获取所有权?

我正在尝试创建一个查找所有用户配置文件的脚本。90 天或更长时间未访问的配置文件将被删除。我还想从 C:\Users 中删除它们的文件夹以释放硬盘空间。

cd C:\Users\
foreach ($dir in $OlderDays) {
    Get-CimInstance -ComputerName $ComputerName -Class Win32_UserProfile -ErrorAction Stop | Where-Object {$_.Special -eq $false}

    Get-CimInstance -ComputerName $profile.ComputerName -ClassName Win32_UserProfile -ErrorAction Stop | Where-Object {$_.SID -eq $profile.RegKey.SID -and $_.LocalPath -eq $profile.RegKey.LocalPath} | Remove-CimInstance -ErrorAction Stop 

    Remove-item -force -Path $dir -recurse
}

我尝试从 C:\Users 中删除每个文件夹,但都被拒绝访问。

我使用的是管理员帐户。到目前为止,我发现的唯一解决方案是 takeown,但有些工作站有 50 多个帐户需要删除,而右键单击文件夹并单击删除需要 10 秒钟,这不太省时。Takeown 每个帐户大约需要 10 分钟。

remove-item : Access to the path 'C:\Users\test5456\AppData\Local\Application Data' is denied.
At line:59 char:5
+     remove-item -force -Path C:\Users\$dir -recurse
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Users\test5456:String) [Remove-Item], UnauthorizedAccessExcepti 
   on
    + FullyQualifiedErrorId : RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.RemoveItemCommand

以管理员身份运行

答案1

即使您以管理员身份运行它,您仍然必须拥有该文件夹(及其内容)的所有权,然后才能删除它。

Takeown 每个帐户大约需要 10 分钟。

TakeOwn 非常慢,使用 PowerShell 的 Get-ACL 和 Set-ACL 更快。

要将文件夹及其所有内容的所有者设置为内置的管理员组,它将是这样的(未经测试):

$Group = New-Object System.Security.Principal.NTAccount("Builtin", "Administrators")
$ACL = Get-ACL $dir
$ACL.SetOwner($Group)

Get-ChildItem $dir -Recurse -Force | % {
    Set-ACL -AclObject $ACL -Path $_.fullname
}

将其放在 Foreach 循环内,Remove-Item 命令之前。

答案2

您不需要这样做。Windows 将使用名为的组策略为您执行此操作:

指定天数后删除用户配置文件。

此外,已经提供了一个名为的工具来执行此操作delprofdelprof2如果您想手动执行此操作。它也可以在远程计算机上执行。

答案3

推荐的解决方案对我来说大部分都有效,但是:

  • 大多数情况下,这意味着接近 50% 的个人资料仍然无法获得权限,因此不会被删除。
  • 与以下解决方案相比,每个项目所花费的时间相当高:

对我有用的是使用cmd /c "rmdir $dir /s /q"删除命令,因此在您的情况下它将是:

cd C:\Users\
foreach ($dir in $OlderDays) {
    Get-CimInstance -ComputerName $ComputerName -Class Win32_UserProfile -ErrorAction Stop | Where-Object {$_.Special -eq $false}

    Get-CimInstance -ComputerName $profile.ComputerName -ClassName Win32_UserProfile -ErrorAction Stop | Where-Object {$_.SID -eq $profile.RegKey.SID -and $_.LocalPath -eq $profile.RegKey.LocalPath} | Remove-CimInstance -ErrorAction Stop 

    cmd /c "rmdir $dir /s /q"
}

此解决方案速度更快,到目前为止,它已在一台计算机中删除了一百多个配置文件,没有出现任何故障。PowerShell 功能强大,我们不得不求助于调用 cmd 来完成这项工作,这很遗憾,但是...

在这里找到了解决方案:https://forums.ivanti.com/s/article/Folder-delete-actions-fail-when-the-folder-contains-a-Junction-soft-link?language=en_US

答案4

正如 @Ramhound 所评论的,如果您要删除旧的用户配置文件,请不要通过删除 C:\Users\username 来实现。首先,从 PC 中删除配置文件并等待几分钟。如果一切正常,删除配置文件将自动删除文件夹结构。如果配置文件仍然存在,那么尝试删除文件夹(如您尝试的那样)将引发各种权限错误。

相关内容请参见

https://www.business.com/articles/powershell-manage-user-profiles/

https://community.spiceworks.com/how_to/124316-delete-user-profiles-with-powershell

Power Shell 脚本用于将用户配置文件从 Windows Server 2008 R2 删除到本地计算机(Windows 7)

相关内容