Powershell 输入带屏蔽的密码
我有一个简单的例子,是从其他一些帖子中拼凑出来的:Powershell 输入带屏蔽的密码,powershell,Powershell,我有一个简单的例子,是从其他一些帖子中拼凑出来的: [CmdletBinding( DefaultParameterSetName = 'Secret' )] Param ( [Parameter(Mandatory=$True)] [string]$FileLocation, [Parameter( Mandatory = $True, ParameterSetName = 'Secret' )] [Securi
[CmdletBinding(
DefaultParameterSetName = 'Secret'
)]
Param (
[Parameter(Mandatory=$True)]
[string]$FileLocation,
[Parameter(
Mandatory = $True,
ParameterSetName = 'Secret'
)]
[Security.SecureString]${Type your secret password},
[Parameter(
Mandatory = $True,
ParameterSetName = 'Plain'
)]
[string]$Password
)
if ($Password) {
$SecretPassword = $Password | ConvertTo-SecureString -AsPlainText -Force
} else {
$SecretPassword = ${Type your secret password}
}
Write-Host $SecretPassword
$BSTR = `
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecretPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host $PlainPassword
在运行脚本时,如何使输入的密码被屏蔽
因此,与此相反:
PS C:\temp> .\test.ps1 -FileLocation C:\Temp\file.csv -Password secret
这个
参数执行以下操作:
-组合字符串
指示cmdlet显示星号(*)以代替用户输入的字符
首先,你的例子不会发生。您的意思是,您希望在脚本执行之前,无论他们从哪个shell执行脚本,都能屏蔽密码,因为密码是作为参数输入的。没有发生 现在,另一种选择是不接受密码作为参数,而是每次都提示输入密码。在这种情况下,您可以将整个
If($Password)
语句简化为:
$SecretPassword = Read-Host 'Type your secret password' -AsSecureString
首先使用以下语句捕获密码:
$password = Read-Host "Enter Your Password" -AsSecureString
这将屏蔽用户在屏幕上输入的字符
但不能直接使用此字符串。要在脚本中使用此安全字符串,需要将其转换为二进制字符串:
$Newpass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
然后使用
$Newpass
作为用户输入的密码。在上面的代码中,-AsSecureString应该指定在哪里?@dross无论您在哪里${Type your secret password}
作为函数或脚本的参数键入的密码都不能以这种方式屏蔽。您可以提示输入密码,使用参数接收密码不会达到屏蔽密码的目的。
$Newpass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))