无法使用自动 powershell 脚本加入域 -- "unable to update password"

failed to join domain with automated powershell script -- "unable to update password"

我正在尝试使用 Powershell 脚本将主机添加到域中。当通过 CloudFormation 或 Ansible 调用脚本时,脚本失败并显示以下错误。当我在主机上手动 运行 时它成功了。

我怀疑我对用户做错了什么(我手动 运行 作为管理员)所以我一直试图强迫它 运行 作为管理员。不幸的是,这也没有用。

有人以前见过这个问题吗?

错误:

> [DEBUG] Command 4-add-to-domain output: Add-Computer : Computer
> 'WIN-xxxxx' failed to join domain 
> 
> 'aws.cloud.bp.com' from its current workgroup 'WORKGROUP' with
> following error 
> 
> message: Unable to update the password. The value provided as the
> current 
> 
> password is incorrect.
> 
> At line:1 char:1
> 
> + Add-Computer -DomainName $domain -Credential $credential -OUPath $ouPath 
> 
> -Restar ...
> 
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 
> ~~~
> 
>     + CategoryInfo          : OperationStopped: (WIN-K9DU7TO9331:String) [Add- 
> 
>    Computer], InvalidOperationException
> 
>     + FullyQualifiedErrorId : FailToJoinDomainFromWorkgroup,Microsoft.PowerShe 
> 
>    ll.Commands.AddComputerCommand

PS1:

if ((gwmi win32_computersystem).partofdomain -eq $true)
{ 
    write-host "already in domain" 
}
else
{
    $domain = $domainname
    $password = $password | ConvertTo-SecureString -asPlainText -Force
    $username = $uid
    $credential = New-Object System.Management.Automation.PSCredential($username,$password)
    $ouPath = $oupath
    $cmd = 'Add-Computer -DomainName $domain -Credential $credential -OUPath $ouPath -Restart'
    $runas = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()

    if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {   
        $log = "not running as admin"
        $log | out-file -Filepath $logger -append
    } else {
        $log = "running as admin, about to run $cmd"
        $log | out-file -Filepath $logger -append
        Invoke-Expression -Command $cmd

    }
}

您尝试过不使用 ConvertTo-SecureString 的密码吗?只是为了测试吗?当我尝试远程更改域上的本地管理员密码时,我遇到了一些问题。据我所知,当您将其转换为安全字符串然后将其分配为变量时,实际密码似乎丢失了。现在,我是一个真正的 powershell 新手,但我只能在直接调用 ConvertTo-SecureString 时让它工作,而不是作为变量。

我不确定为什么当您手动 运行 它时它会工作,但这是我首先尝试尝试隔离问题的方法。如果我跑题了,请随时纠正我。

答案比我想象的要简单:当脚本通过自动化工具(CloudFormation 或 Ansible)运行 时,它是 运行 作为本地管理员。然而,手动它是 运行 作为 domain\admin。因此我需要做的是用用户名 $username = "mydomain\my-domain-user" 来调用它,而不是简单地 "my-domain-user"。 希望这对遇到同样问题的人有所帮助...

取自:http://www.gi-architects.co.uk/2017/01/powershell-add-computer-error-when-executed-remotely/

问题的根源是(假设您的密码正确)当 运行 交互时,域是预先附加的,因此您只需要提供用户。但在非交互式环境中,域本身并不为人所知这是一个非常简单的修复,请确保您包括短域名,如“contoso\DMAdmin”或完整的 FQDN“DMAdmin@contoso.com .