阅读PowerShell中的单个按键 [英] Read individual key presses in PowerShell

查看:107
本文介绍了阅读PowerShell中的单个按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PowerShell,我想在按键按下时读取它们的值,而无需用户按下Enter键.例如,如果用户按下"1",我希望PowerShell脚本在没有输入"的情况下立即对选择做出反应.

Using PowerShell, I would like to read the value of key presses as they occur, without the user having to press enter. For example, if the user presses '1' I would like the PowerShell script to react to the choice immediately without an 'enter'.

我的研究发现了ReadKey,

My research has turned up ReadKey,

$ input = $ Host.UI.RawUI.ReadKey('IncludeKeyDown');

$input = $Host.UI.RawUI.ReadKey('IncludeKeyDown');

但是ReadKey在字符串中返回的信息远远超过我的要求:

But ReadKey returns much more information in the string than I require:

72,h,0,真

72,h,0,True

虽然我可以从该字符串中解析按键,但我更喜欢一个更直接的选项.是否存在?

While I can parse the key press from this string, I'd prefer a more direct option. Does one exist?

推荐答案

也许您可以澄清一下-但ReadKey返回

Perhaps you could clarify a bit - but ReadKey returns a KeyInfo object not a string. KeyInfo contains VirtualKeyCode, Character, ControlKeyState and KeyDown members - all fields in your output string in that order. In fact, it looks like PowerShell has just called the .ToString() method in your output example. You will probably want to look at the Character property to find your desired character. Consider the following example where I press 1:

$key = $Host.UI.RawUI.ReadKey()
if ($key.Character -eq '1') {
  "Pressed 1"
}

这篇关于阅读PowerShell中的单个按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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