在PowerShell中提示用户input

我想提示用户一系列的input,包括密码和文件名。

我有一个使用host.ui.prompt的例子,这似乎是明智的,但我不明白的回报。

有没有更好的方法来获取用户inputPowerShell?

Read-Host是从用户获取stringinput的简单选项。

 $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()返回的types,如果你在@ Christian的注释中发布的链接上运行代码,你可以通过pipe道将它返回给Get-Member (例如$results | gm )。 结果是一个Dictionary,其中的键是提示中使用的FieldDescription对象的名称。 要访问链接示例中第一个提示的结果,您应该input: $results['String Field']

要在不调用方法的情况下访问信息,请closures括号:

 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将给你方法的定义。 每个定义显示为<Return Type> <Method Name>(<Parameters>)

使用参数绑定绝对是这里的方法。 不仅写起来很快(只要在你的强制性参数上面加上[Parameter(Mandatory=$true)] ,而且它也是你以后不会憎恨自己的唯一select。

更多下面:

[Console]::ReadLine被PowerShell的FxCop规则显式禁止。 为什么? 因为它只能在PowerShell.exe中使用,而不能在PowerShell ISE , PowerGUI等中使用。

Read-Host很简单,就是坏的forms。 读主机不可控制地停止脚本以提示用户,这意味着您永远不会拥有包含使用Read-Host的脚本的其他脚本。

你正在试图询问参数。

你应该使用[Parameter(Mandatory=$true)]属性,并且正确input,以询问参数。

如果你在[SecureString]上使用它,它会提示input密码字段。 如果您在凭证types( [Management.Automation.PSCredential] )上使用此凭证,则凭据对话框将popup,如果参数不存在。 一个string将会变成一个普通的旧文本框。 如果你添加一个HelpMessage到参数属性(即[Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')] ),那么它将成为提示的帮助文本。

将其放置在脚本的顶部。 这将导致脚本提示用户input密码。 最终的密码可以通过$ pw在脚本的其他地方使用。

  Param( [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")] [SecureString]$password ) $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)) 

如果您想debugging并查看您刚读取的密码的值,请使用:

  write-host $pw 

作为替代scheme,您可以将其作为脚本参数作为脚本执行的一部分添加到input中

  param( [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1, [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2 )