我正在尝试保护我的密码并将其存储在一个文件中,这样我每次运行脚本时都不需要输入。
第一步,我运行以下命令,输入存储在E:\ cred.txt文件中的密码。 txt文件现在包含加密密码。
(Get-Credential).Password | ConvertFrom-SecureString | Out-File "E:\cred.txt"
其次,我运行以下脚本:
$File = "E:\cred.txt"
$User = "jason@domain.com"
#### I have two different user accounts, one for admin and other for operator,
#### however both user accounts use same password.
$adminuser = $User
$operator = $User -replace "@domain.com"
#### I would need to read $File to get only the password
$pass = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList (Get-Content $File | ConvertTo-SecureString)
$adminuser
$operator
$pass
输出:
jason@domain.com
jason
UserName Password
-------- --------
从输出中,似乎New-Object同时指UserName和Password。当我尝试连接到系统时,它会因身份验证错误而失败。由于我已经在脚本中硬编码了两个不同的用户名,我应该如何只获得$ pass中存储的密码?或者是否可以将所有用户名($ User,$ adminuser,$ operator)包含在cred.txt文件中?
答案 0 :(得分:0)
试试这个:
#saving credentials
Get-Credential | Export-CliXml -Path c:\credential.xml
#importing credentials to a variable
$Credential = Import-CliXml -Path c:\credential.xml
或者这个:
#you could then write it to a file or, i say its a better approach to a registry key
$SecurePassword = ConvertTo-SecureString -String 'P@ssw0rd' -AsPlainText -Force | ConvertFrom-SecureString
#now you are taking it back as a secure string
$RegistrySecureString = $SecurePassword | ConvertTo-SecureString
#you can aslo see the password
$UserName = "NULL"
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $RegistrySecureString
$Password = $Credentials.GetNetworkCredential().Password
#P@ssw0rd