我想提示用户进行一系列的输入,包括密码和文件名。
我有一个使用host.ui.prompt
的例子,这似乎是合理的,但我无法理解其返回。
有没有更好的方法在PowerShell中获得用户输入?
Read-Host
是一个简单的选项,用于从用户那里获得字符串输入。
$name = Read-Host 'What is your username?'
为了隐藏密码,你可以使用。
$pass = Read-Host 'What is your password?' -AsSecureString
要将密码转换为纯文本。
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
至于$host.UI.Prompt()
返回的类型,如果你运行@Christian'评论中发布的链接中的代码,你可以通过管道输入Get-Member
(例如,$results | gm
)来了解返回类型。结果是一个字典,其中的键是提示中使用的FieldDescription
对象的名称。在链接的例子中,要访问第一个提示的结果,你需要键入。$results['String Field']
。
要在不调用方法的情况下访问信息,可以不加圆括号。
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions
会给你方法的定义。每个定义都显示为<返回类型> <方法名称>(<参数>)
。
在这里,使用参数绑定绝对是个好办法。它不仅编写起来非常快(只需在你的强制参数上方添加[Parameter(Mandatory=$true)]
),而且它也是唯一一个你以后不会讨厌自己的选择。
下面有更多内容。
[Console]::ReadLine
是PowerShell的FxCop规则明确禁止的。 为什么? 因为它只在PowerShell.exe中工作,而不是PowerShell ISE、PowerGUI等。
Read-Host很简单,是不好的形式。Read-Host会不受控制地停止脚本以提示用户,这意味着你永远不可能有另一个包括使用Read-Host的脚本的脚本。
你'是在试图询问参数。
你应该使用[Parameter(Mandatory=$true)]
属性,并正确地打字,来询问参数。
如果你在"[SecureString]"上使用这个属性,它将提示一个密码域。 如果你在一个凭证类型([Management.Automation.PSCredential]
)上使用这个,如果参数不在那里,凭证对话框将弹出。一个字符串会变成一个普通的文本框。如果你在参数属性中添加HelpMessage(即[Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
),它将成为提示的帮助文本。
把这个放在你的脚本的顶部。 它将导致脚本提示用户输入密码。 所得到的密码可以通过$pw在脚本的其他地方使用。
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
如果你想调试并查看刚刚读取的密码的值,可以使用。
write-host $pw