【问题标题】:Remove local user and data from windows 10 using powershell使用 powershell 从 Windows 10 中删除本地用户和数据
【发布时间】:2020-06-30 11:37:38
【问题描述】:

我正在尝试从计算机(名为 Deltagare)中删除本地用户。我需要删除帐户以及与C:/Users/username 中的帐户关联的文件。以管理员身份运行脚本时,我遇到了拒绝访问事件的问题。该脚本在管理员帐户上运行。我曾尝试通过使用takeownicaclsSet-Acl 来转移所有权,但我仍然在 Remove-Item 处被拒绝访问

Remove-LocalUser -Name "Deltagare"
# Grant ownership here using takeown, icacls or Set-Acl
Remove-Item -Path "\\?\C:\Users\Deltagare" -Recurse

如何使用 Powershell 删除此文件夹?关于如何获得所有权或我需要以其他方式删除用户的任何想法?

【问题讨论】:

标签: powershell windows-10 file-permissions file-access


【解决方案1】:

在我看来,这对于 CIM/WMI 来说是最简单的。但是,您可能希望在删除用户帐户之前将其删除。

Get-CimInstance -ClassName Win32_UserProfile |
    Where-Object { $_.LocalPath.EndsWith($UserName) } |
    Remove-CimInstance -WhatIf

当然,删除-Whatif 参数以实际删除配置文件。

按 SID 过滤可能比按本地路径中的用户名过滤更好。

【讨论】:

  • 有时本地路径以“.001”等结尾。
  • @js2010 绝对是。这就是我推荐 SID 查找的原因之一。
【解决方案2】:

这是一种获取 sid 并使用 sid 删除配置文件的方法。这将处理文件夹和它的注册表项。

$sid = get-ciminstance win32_useraccount | where name -eq myuser | % sid
get-ciminstance win32_userprofile | where sid -eq $sid | Remove-CimInstance -whatif

【讨论】:

    【解决方案3】:

    删除本地帐户听起来像是一项任务,但它至少包含以下三个步骤:

    1. 从本地帐户数据库中删除帐户
    2. 删除此帐户的个人资料目录
    3. 从注册表中删除帐户配置文件

    以下函数将执行这三个任务:

    function Remove-LocalUserCompletely {
    
        Param(
            [Parameter(ValueFromPipelineByPropertyName)]
            $Name
        )
    
        process {
            $user = Get-LocalUser -Name $Name -ErrorAction Stop
    
            # Remove the user from the account database
            Remove-LocalUser -SID $user.SID
    
            # Remove the profile of the user (both, profile directory and profile in the registry)
            Get-CimInstance -Class Win32_UserProfile | ? SID -eq $user.SID | Remove-CimInstance
        }
    }
    
    # Example usage:
    Remove-LocalUserCompletely -Name 'myuser'
    

    您可以在my answer on SU 中阅读有关删除本地用户帐户/配置文件的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 2017-11-17
      相关资源
      最近更新 更多