可以使用 ADSI 为需要在首次登录时更改的 windows 帐户设置密码

Can ADSI be used to set password for windows account requiring change at first logon

我有这个 PowerShell 脚本的修改版本:https://social.technet.microsoft.com/Forums/scriptcenter/en-US/355d9293-e324-4f60-8eed-18bcc6d67fc0/adsiwinntcomputeradministratoruser-with-alternate-credentials?forum=ITCG

尝试更改具有首次登录要求的帐户的密码时失败(我可以使用 ctrl+alt+del 提示手动更改密码,但 运行 经常这样做图像上的 VM 测试)。重要的部分是:

Invoke-Command -ComputerName $ComputerName -Credential $Credential -ErrorVariable e -ArgumentList $ComputerName,$NewPassword,$User -ScriptBlock {
            Param($ComputerName,$NewPassword,$User)
            $Account = [ADSI]"WinNT://$ComputerName/$User,user"
            $Account.PwdLastSet = 0
            $Account.SetInfo()
            $Account.SetPassword($NewPassword)
            $Account.SetInfo()
            $e
        }

当我 运行 第一次登录不需要更改的帐户时,它成功完成:

> Change-LocalPassword -User 'TestAccount' -Credential $wincred -OldPassword $OP -NewPassword $NP -ComputerName $computerName
Info::Change-LocalPassword::Changing password from <old> to <new>
Info::Change-LocalPassword::Service WinRM is already running on Localhost
Info::Change-LocalPassword::Trusted Hosts Value is: <computer>
Info::Change-LocalPassword Invoking Command: [adsi]WinNT://<computer>/TestAccount,user
True

当运行需要首次登录的帐户时:

Change-LocalPassword -User $Config.win_user -Credential $wincred -OldPassword $Config.winog_passwd -NewPassword $Config.win_passwd -ComputerName $computerName
Info::Change-LocalPassword::Changing password from <old> to <new>
Info::Change-LocalPassword::Service WinRM is already running on Localhost
Info::Change-LocalPassword::Trusted Hosts Value is: <computer>
Info::Change-LocalPassword Invoking Command: [adsi]WinNT://<computer>/<user>,user
[computer] Connecting to remote server <computer> failed with the following error message : Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (<computer>:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
-Message Error::Change-LocalPassword::Could not set password for <user> on <computer> [computer] Connecting to remote server <computer> failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
False

本地管理员帐户是计算机上的唯一帐户,未加入域。有没有其他人遇到过这个并确定了解决方案?

添加密码永不过期用户标志:

$Account = [ADSI]"WinNT://$ComputerName/$User,user"
        $Account.UserFlags = 65536
        $Account.PwdLastSet = 0
        $Account.SetInfo()
        $Account.SetPassword($NewPassword)
        $Account.SetInfo()

如果您还想添加 "user can't change password",请用这一行替换上面的行:

$Account.UserFlags = 64 + 65536