繁体   English   中英

通过 powershell 脚本将本地用户添加到管理员组时出现问题

[英]Issues adding a local user to the administrators group via a powershell script

我被分配了一个任务来制作以下脚本:

  • 检查账户是否存在
  • 如果没有,请创建一个帐户
  • 检查帐户是否属于本地管理员
  • 如果没有,添加到本地管理员组
  • 生成随机密码
  • 设置账户密码为随机密码

我遇到问题的地方是检查该帐户是否存在,如果存在,那么它应该是本地管理员组的一部分。 当尝试通过 powershell 脚本添加用户时,出现以下错误:

The 'Administrators' group members are null.
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

到目前为止,这是脚本。

try {
    # Check if the account exists
    $username = "chappie"
    $user = Get-LocalUser -Name $username
    # If not, create an account
    if (!$user) {
        New-LocalUser -Name $username -NoPassword -FullName "Chappie User" -Description "Chappie user account"
        $user = Get-LocalUser -Name $username
    }
}
catch {
    if ($_) {
        Write-Error "Error creating user account: $_"
    }
    return
}

try {
    # Check if an account is part of local admins
    $adminGroup = Get-LocalGroup -Name "Administrators"
    if (!$adminGroup) {
        Write-Error "The 'Administrators' group object is null."
        return
    }
    if ($adminGroup.Members -eq $null) {
        Write-Error "The 'Administrators' group members are null."
        return
    }
    $admin = $adminGroup.Members | Where-Object { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -eq "Chappie" }
    # If not, add to the local admins group
    if (!$admin) {
        $user = Get-LocalUser -Name "Chappie"
        if (!$user) {
            Write-Error "The 'Chappie' user object is not found."
            return
        }
        $userPrincipal = $user.SID
        if (!$userPrincipal) {
            Write-Error "The 'Chappie' user principal is null."
            return
        }
        $adminGroup.Invoke("Add", $userPrincipal.Value)
    }
}
catch {
    if ($_) {
        Write-Error "Error adding user to local administrators group: $_"
    }
    return
}

`

任何建议都会有所帮助。 谢谢!

由于管理员组错误为 null,因此我继续为该组添加检查以确保它不是 null 并且它仍然返回相同的结果。 我还验证了用户创建已经完成并且组也已创建。

使用Get-LocalGroupMemberAdd-LocalGroupMember cmdlet,例如

try {
    # Check if the account exists
    $username = "chappie"
    $user = Get-LocalUser -Name $username -ErrorAction SilentlyContinue
    # If not, create an account
    if (!$user) {
        $user = New-LocalUser -Name $username -NoPassword -FullName "Chappie User" -Description "Chappie user account"
    }
    # Check if an account is part of local admins
    $adminGroup = Get-LocalGroupMember "Administrators"
    # If not, add to the local admins group
    if (!($adminGroup.SID.Value -contains $user.SID)) {
        Add-LocalGroupMember -Member $user -Group 'Administrators'
    }
}
catch {
    Write-Host '$_ is' $_
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM