我正在使用 powershell 动态创建虚拟机(在带有 Windows Server 2012 R2 的 ESX 上)。我已经准备好了大部分自动化部分,但是当我们在配置后第一次登录虚拟机时重置管理员密码(作为 Windows 安全策略的一部分),我遇到了困难。
我尝试过类似以下的方法(但不起作用):
[ADSI]$vmAccount="WinNT://$vmName/$vmUserName"
$vmAccount.ChangePassword($current, $new)
它失败了:
Exception calling "ChangePassword" with "2" argument(s):
"The specified network password is not correct.
非常感谢任何为我指明正确方向的帮助。
这对我来说是远程的,你可以尝试一下:
$comp = <computer>
$user = <Username here>
$pass = <New password here>
("WinNT://$comp/$user/").SetPassword($pass)
如果这不起作用,您可能需要检查安全策略并查看密码是否符合安全策略,powershell 错误有时可能非常平淡。
错误
Exception calling "ChangePassword" with "2" argument(s): "The specified network password is not correct.
是由于您的密码中的符号引起的。例如,如果您的密码中有“$”,PoweShell 会将其视为变量。
在PowerShell中,美元符号$用于引用变量。当您的密码包含美元符号时,PowerShell 可能会将其解释为变量并尝试将其替换为变量的值,从而导致意外行为。
为了防止 PowerShell 将美元符号解释为变量,可以在脚本中定义密码时使用单引号 (') 代替双引号 (")。单引号可以防止变量扩展,美元符号将被视为变量一个字面字符。
在您的情况下,您需要读取安全字符串中的密码,然后将其转换为明文以设置密码,如下所示:
$username = Read-Host -Prompt "Enter the AD user's username"
$domainController = "foo.example.local" #You can also provide IP of DC
$currentPassword = Read-Host -Prompt "Enter the current password" -AsSecureString
# Convert the secure string for current password to plain text
$plainCurrentPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($currentPassword))
$newPassword = Read-Host -Prompt "Enter the new password" -AsSecureString
# Convert the secure strings to plain text
$plainNewPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($newPassword))
[ADSI]$useraccount="WinNT://$domainController/$username"
$useraccount.ChangePassword($plainCurrentPassword, $plainNewPassword)
或者以简单的方式了解它如何与纯文本一起工作,请参见下文(不推荐,因为它将您的密码存储为文本):
$user.ChangePassword('$abcd1234', '$qwerty1234')