使用param()时如何显示在Power Shell中输入密码的提示

时间:2018-06-27 05:06:38

标签: windows powershell

如何使密码字段在功能的参数上下文中作为提示显示给用户?

这是我已经拥有的代码:

param(
  [Parameter(Mandatory=$true,HelpMessage="Enter Appliance Host Name")][string]$hostname,
  [Parameter(Mandatory=$true,HelpMessage='Enter Appliance Username')][string]$username,
  [Parameter(Mandatory=$true,HelpMessage='Enter Appliance Password')][string]$password,

  [Parameter(Mandatory=$false,HelpMessage='Enter Appliance Proxy if required')][string]$proxy=""
)

1 个答案:

答案 0 :(得分:1)

您可以在函数的参数部分中运行方法。

尝试像这样运行它:

param(
  [Parameter(Mandatory=$true,HelpMessage="Enter Appliance Host Name")][string]$hostname,
  [Parameter(Mandatory=$false,HelpMessage="Enter Credentials here")][System.Management.Automation.PSCredential]$Credential = (Get-Credential)
  [Parameter(Mandatory=$false,HelpMessage='Enter Appliance Proxy if required')][string]$proxy=""
)

您还可以将用户名和密码直接解析到该函数,并在该函数中创建凭据对象:

param(
  [Parameter(Mandatory=$true,HelpMessage="Enter Appliance Host Name")][string]$hostname,
  [Parameter(Mandatory=$true,HelpMessage='Enter Appliance Username')][string]$username,
  [Parameter(Mandatory=$true,HelpMessage='Enter Appliance Password')][string]$password,
  [Parameter(Mandatory=$false,HelpMessage='Enter Appliance Proxy if required')][string]$proxy=""
)
$password = ConvertTo-Securestring -string $password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ("$username", $password)