删除本地用户主目录 powershell

Delete Local User Home Dir powershell

function deleteUsers($hash) {
   foreach ($h in $hash.GetEnumerator()) {
    Try
    {
        Remove-LocalUser -Name $($h.Name)
    }
    Catch{
        "Can't Delete User {0}" -f $($h.Name)
    }
   }
}

function createUsers($hash) {
   foreach ($h in $hash.GetEnumerator()) {

    $Password = ConvertTo-SecureString $($h.Value) –AsPlainText –Force
    New-LocalUser -Name $($h.Name) -Password $Password -AccountNeverExpires -FullName $($h.Name) -PasswordNeverExpires -UserMayNotChangePassword
    Add-LocalGroupMember -Group "Users" -Member $($h.Name)
   }
}


$users = @{"User blabla" = "pass"; 
           "User blabla2" = "pass2"
        }

createUsers($users)
deleteUsers($users)

这个基本的 powershell 工作正常,但就是不删除用户主目录,我应该向 deleteUsers 函数添加什么来解决这个问题?我找不到一种简单的方法来实现 Get-LocalUser。我只看到 Get-ADUser 的解决方案:/

我想要一个与下面同类的解决方案

$homeDir = Get-LocalUser -Name $($h.Name) -Properties HomeDirectory | Select -ExpandProperty HomeDirectory

    If (Test-Path $homeDir) 
    {
        Remove-Item -Path $homeDir -Force
    }

非常感谢

感谢 TheIncorrigible1,我终于完成了这个

function deleteUsers($hash) {
   foreach ($h in $hash.GetEnumerator()) {
    Try
    {
        Remove-LocalUser -Name $($h.Name)
        $pathUser = "C:\Users\{0}" -f "$($h.Name)" 
        $profile = GWMI -class Win32_UserProfile -Filter "LocalPath='$pathUser'"
        $profile.Delete()
        "[ OK ]User {0} deleted" -f $($h.Name)
    }
    Catch{
        "Can't Delete User {0}" -f $($h.Name)
    }
   }
}

我不建议将配置文件路径构造为 "C:\Users\{0}" -f $h.Name,然后按该路径过滤 Win32_UserProfile。不能保证用户的个人资料将始终位于 C:\Users\<username> 中。通常更好的方法是:

  1. 确定用户的SID:

    $name = 'someuser'
    $fltr = "name='${name}' and domain='${env:computername}'"
    $sid  = Get-WmiObject Win32_UserAccount -Filter $fltr |
            Select-Object -Expand SID
    

    $name = 'someuser'
    $acct = New-Object Security.Principal.NTAccount($name)
    $sid  = $acct.Translate([Security.Principal.SecurityIdentifier]).Value
    
  2. 使用 SID 查找和删除配置文件:

    Get-WmiObject Win32_UserProfile -Filter "sid='${sid}'" | ForEach-Object {
        $_.Delete()
    }
    
  3. 删除账号:

    Remove-LocalUser -Name $name
    

    或(如果您 运行 是 Windows 的旧版本)

    ([adsi]'WinNT://.').Delete('user', $name)
    

按照这个顺序。

如果您已经删除了一个帐户并需要删除孤立的个人资料,您可以过滤Win32_UserProfile 以查找参考计数为零的个人资料:

Get-WmiObject Win32_UserProfile -Filter 'refcount=0' | ForEach-Object {
    $_.Delete()
}

此外,请注意 $profile 是一个 automatic variable with the path to your PowerShell profile,因此您不应将该变量用于其他用途。