如何在PowerShell中把密码保存到文件

来源:互联网 发布:java离线安装包 32位 编辑:程序博客网 时间:2024/05/16 18:26


我相信许多人在PowerShell写交互代码的时候,都通常会用Read-Host结合AsSecureString参数配合使用,让用户输入密码。又或者运用Get-Credential cmdlet凭据把用户名和密码保存为一个变量对象,但很多时候我们又想让用户输入的这个密码对象重复使用,可往往很多.NET类都无法直接去处理这个密码对象。

如下我们举例来看看之前提到的几个问题,以及如何解决密码重用的办法。

如图我们用Get-Credential cmdlet让用户输入了密码。在这里我们用Get-Member cmdlet可以看到该变量对象下面有一个Password属性。

PS C:\Windows\system32> $Credential | Get-Member   TypeName: System.Management.Automation.PSCredentialName                 MemberType Definition----                 ---------- ----------Equals               Method     bool Equals(System.Object obj)GetHashCode          Method     int GetHashCode()GetNetworkCredential Method     System.Net.NetworkCredential GetNetworkCredential()GetType              Method     type GetType()ToString             Method     string ToString()Password             Property   System.Security.SecureString Password {get;}UserName             Property   System.String UserName {get;}

我们调用Password属性看一看,发觉并不能看到所谓的密码。而且这也并不是一个纯文本信息,在这种情况下也就无法达到我们所说的复用。

PS C:\Windows\system32> $Credential.PasswordSystem.Security.SecureString

为了能够让我们的密码得到复用,这里我们要借用ConvertFrom-SecureString cmdlet,如下它帮助我们生成了一串纯文本信息内容,我们就可以拿这串内容保存到文本文件内。

PS C:\Windows\system32> ConvertFrom-SecureString -SecureString $SecurePassword01000000d08c9ddf0115d1118c7a00c04fc297eb010000007033a3eb11c8d34dbf52756fe1862db60000000002000000000003660000c0000000100000003cda3a4f88251d1f02747feb90ed38730000000004800000a000000010000000b622cf9be93353c6c2fb8823da4738a1180000005ac5a3c578406fa8033de6a29a6e160700c0bc0d7e622079140000002fbf81c0d0486c1a9aa8b30aabf788cb332578ae

0 0
原创粉丝点击