powershell - 如何在Powershell中将用户添加到本地管理员组?

标签 powershell

我正在尝试使用Powershell在远程计算机上创建用户。创建帐户后,我想将其添加到本地管理员组中。

正在创建帐户,但未将其添加到管理组中。下面是我正在使用的代码。

  cls
  $username = "test_user"
$password = "password"
$computer1 = hostname
  $users = $null
   $computer = [ADSI]“WinNT://$computer1”
   Try {
      $users = $computer.psbase.children | select -expand name  
      if ($users -like $username) {
         Write-Host "$username already exists"
      } Else {
         $user_obj = $computer.Create(“user”, “$username”)
         $user_obj.SetPassword($password)
         $user_obj.SetInfo()

         $user_obj.Put(“description”, “$username”)
         $user_obj.SetInfo()
         $user_obj.psbase.invokeset(“AccountDisabled”, “False”)
         $user_obj.SetInfo()
         $users = $computer.psbase.children | select -expand name
         if ($users -like $username) {
            Write-Host "$username has been created on $($computer.name)"

            $group = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/administrators,group")
$group.add("WinNT://$env:localhost/$username,user")


         } Else {



            Write-Host "$username has not been created on $($computer.name)"
         }
      }
   } Catch {
      Write-Host "Error creating $username on $($computer.path):  $($Error[0].Exception.Message)"
   }

我究竟做错了什么?

最佳答案

$env:computername是您的本地计算机。 $env:localhost不存在。 $computer1是您为要向其添加用户的计算机定义的变量。

$group = [ADSI]("WinNT://$computer1/administrators,group")
$group.add("WinNT://$computer1/$username,user")

关于powershell - 如何在Powershell中将用户添加到本地管理员组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47946668/

相关文章:

powershell - 错误操作未停止脚本

visual-studio - 如何在Visual Studio中动态创建解决方案的解决方案文件夹?

c# - 使用自己的 PowerShell CmdLets 将管理命令发送到我的 C# Windows 服务

PowerShell : retrieve JSON object by variable value

azure - 从 AzureAD 安全的 powershell 核心 Azure Function 获取 ClaimsPrincipal/Identity

powershell - 反序列化对象类型问题 - 特别是 Powershell 5 类和 Import-CliXml

powershell - 使用 AzureHDInsightCluster 引发错误

powershell - 如何选择非空CSV单元格并将其放入Powershell中的数组中?

email - 如何使用 PowerShell 将文件附加到电子邮件

powershell - 为什么使用 Get-Variable 访问参数变量的属性只能在 ISE 中第一次工作?