Powershell ReadKey()区分大小写
在我的脚本中,我需要从用户那里获取1个字符,并立即处理它,而不需要等待输入。 此外,我想处理字符区分大小写Powershell ReadKey()区分大小写,powershell,Powershell,在我的脚本中,我需要从用户那里获取1个字符,并立即处理它,而不需要等待输入。 此外,我想处理字符区分大小写 write-host("Please press a or A:") $choice = ($host.UI.RawUI.ReadKey(('NoEcho,IncludeKeyUp,IncludeKeyDown'))).character if($choice -ceq "a") { write-host("You pressed a"); } elseif($choice -c
write-host("Please press a or A:")
$choice = ($host.UI.RawUI.ReadKey(('NoEcho,IncludeKeyUp,IncludeKeyDown'))).character
if($choice -ceq "a")
{
write-host("You pressed a");
}
elseif($choice -ceq "A")
{
write-host("You pressed A");
}
else
{
Write-Host("You pressed neither a nor A")
}
Pause
此代码的问题是当我尝试按“A”时,它显示“您既没有按A也没有按A”。
原因是要键入“A”,我必须先按Shift键,Powershell检测到按下Shift键,它会立即处理,而无需等待A
有人知道如何解决这个问题吗?请尝试以下代码片段:
if ( $Host.Name -eq 'ConsoleHost' ) {
Write-Host "Please press a or A:"
Do {
$choice = $host.UI.RawUI.ReadKey(14)
} until ( $choice.VirtualKeyCode -in @( 48..90) )
if ( $choice.Character -ceq "a") {
Write-Host "You pressed a";
}
elseif ( $choice.Character -ceq "A") {
Write-Host "You pressed A";
}
else {
Write-Host "You pressed neither a nor A ($($choice.Character))";
}
} else {
# e.g. Windows PowerShell ISE Host:
# the "ReadKey" method or operation is not implemented.
Write-Host '$Host.Name -neq ConsoleHost' -ForegroundColor Magenta
}
正如目前编写的,
$choice.VirtualKeyCode-in@(48..90)
条件允许一些(有限的)可打印字符子集。根据……调整它。以下内容是否弥补了预期的不足
($key = $Host.UI.RawUI.ReadKey()) | % { if ($_.VirtualKeyCode -eq '16') {
$key = $Host.UI.RawUI.ReadKey()
}
$Choice = $key.Character
if ($Choice -ceq "a"){
"`rYou pressed 'a'"
}
elseif ($Choice -ceq "A"){
"`rYou pressed 'A'"
}
else {
"`rYou neither pressed 'a' nor 'A'"
}
}
最简单的解决方案是,只对产生可打印字符的按键做出反应,然后评估通过键盘按下的字符 注意:虽然修改键Shift、Control和Alt本身不算作按键,但与可打印字符的组合不算作按键;因此,例如,Alt-a被视为与
'a'
相同,而Control-a被视为标题的控制字符开始
如果要避免这种情况,请使用以下变体:
# Wait for a printable character to be pressed, but only if not combined
# with Ctrl or Alt.
while (($key=$host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')).Character -eq 0 -or
$key.ControlKeyState -notin 0, 'ShiftPressed') {}
$char = $key.Character
注意:这仅适用于Windows—在类Unix平台上,.ControlKeyState
属性显然总是0
但是,如果改用,也可以使其在类似Unix的平台上工作—这假定您愿意假定脚本始终在控制台(终端)中运行,而不是在其他类型的PowerShell主机中运行
# Wait for a printable character to be pressed, but only if not combined
# with Ctrl or Alt.
while (($key = [Console]::ReadKey($true)).KeyChar -eq 0 -or
$key.Modifiers -notin 0, 'Shift') {}
$char = $key.KeyChar
检查文档中是否有e comment//Ignore(如果按Alt或Ctrl键)。
# Wait for a printable character to be pressed, but only if not combined
# with Ctrl or Alt.
while (($key = [Console]::ReadKey($true)).KeyChar -eq 0 -or
$key.Modifiers -notin 0, 'Shift') {}
$char = $key.KeyChar