使用加密的Password.txt更改本地管理员密码

时间:2017-11-29 00:50:37

标签: windows powershell encryption powershell-v4.0

我正在尝试更新本地管理员帐户密码。我不想以纯文本形式传递密码,因此我找到了一个允许我加密PW的工作流程(https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/)。

#Change password for TestAccount
$User = 'TestAccount'
$PasswordFile = "$PsScriptRoot\Password.txt"
$KeyFile = "$PsScriptRoot\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential ` -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)

$adsiUser = [adsi]"WinNT://localhost/$User,user"
$adsiUser.SetPassword($MyCredential.Password)

我收到了错误

Exception calling "SetPassword" with "1" argument(s): "Type mismatch. 
(Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"

所以我的google-fu允许我用

解密密码
$decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($MyCredential.Password))

但现在我的脚本中有一串cookie ...有没有办法将其作为安全字符串传递?

谢谢, 保罗

1 个答案:

答案 0 :(得分:0)

使用内置方法GetNetworkCredential()从凭据对象中获取纯文本密码

所以改变这一行:

$adsiUser.SetPassword($MyCredential.Password)

To This:

$adsiUser.SetPassword($MyCredential.GetNetworkCredential().Password)

简短的凭证保存/加载教程:

#To Save Credential to file
$pass = "123456" | ConvertTo-SecureString -AsPlainText -Force
$pass | ConvertFrom-SecureString | Set-Content c:\temp\pass.txt

#To Load Credential From Text
$username = "userName"
$encrypted = Get-Content c:\temp\pass.txt | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($username, $encrypted) 

#To Show the Plain text Password from the Credential Object
$credential.GetNetworkCredential().Password