在 PowerShell 中提示用户输入 [英] Prompt for user input in PowerShell

查看:101
本文介绍了在 PowerShell 中提示用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提示用户输入一系列内容,包括密码和文件名.

I want to prompt the user for a series of inputs, including a password and a filename.

我有一个使用 host.ui.prompt 的例子,看起来很合理,但我无法理解返回.

I have an example of using host.ui.prompt, which seems sensible, but I can't understand the return.

是否有更好的方法在 PowerShell 中获取用户输入?

Is there a better way to get user input in PowerShell?

推荐答案

Read-Host 是一个从用户那里获取字符串输入的简单选项.

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

要隐藏密码,您可以使用:

To hide passwords you can use:

$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'].

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

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

To access information without invoking a method, leave the parentheses off:

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 会给你方法的定义.每个定义显示为 ;<方法名称>(<参数>).

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

这篇关于在 PowerShell 中提示用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆