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



我相信许多人在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.PSCredential

Name                 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.Password
System.Security.SecureString

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

PS C:\Windows\system32> ConvertFrom-SecureString -SecureString $SecurePassword
01000000d08c9ddf0115d1118c7a00c04fc297eb010000007033a3eb11c8d34dbf52756fe1862db60000000002000000000003660000c0000000100
000003cda3a4f88251d1f02747feb90ed38730000000004800000a000000010000000b622cf9be93353c6c2fb8823da4738a1180000005ac5a3c578
406fa8033de6a29a6e160700c0bc0d7e622079140000002fbf81c0d0486c1a9aa8b30aabf788cb332578ae

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值