使用secureString检索密码

时间:2018-06-22 17:30:03

标签: powershell powershell-v3.0 powershell-v4.0

我正在创建一个文件,其密码如下所示,并使用secureString

[string][ValidateNotNullOrEmpty()]$secureStringPwd = "password123"
$secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
$secureStringText = $secpasswd | ConvertFrom-SecureString 
Set-Content "C:\folder\user.txt" $secureStringText

现在我正尝试通过以下方式检索密码

$Password = Get-Content "C:\folder\user.txt" | ConvertFrom-SecureString 

$creds = New-Object System.Management.Automation.PSCredential ("user", $Password)
$creds.Password
$creds.UserName

但是我收到如下错误:

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:1 char:10
+ $creds = New-Object System.Management.Automation.PSCredential ("user ...
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

1 个答案:

答案 0 :(得分:2)

您需要将密码从文本文件转换回安全字符串

$Password = Get-Content "C:\folder\user.txt" | ConvertTo-SecureString

此外,您还需要使用网络凭据将密码转换为纯文本格式

$creds.GetNetworkCredential().Password

这是一个可行的例子

[string][ValidateNotNullOrEmpty()]$secureStringPwd = "password123"
$secpasswd = ConvertTo-SecureString $secureStringPwd -AsPlainText -Force
$secureStringText = $secpasswd | ConvertFrom-SecureString 
Set-Content "C:\folder\user.txt" $secureStringText

$Password = Get-Content "C:\folder\user.txt" | ConvertTo-SecureString 

$creds = New-Object System.Management.Automation.PSCredential ("user", $Password)
$creds.GetNetworkCredential().Password
$creds.UserName