在我的脚本中,我需要从用户那里获得一个字符,并且在没有等待进入的情况下立即处理它。此外,我想处理字符区分大小写。
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检测按下的移位并立即处理,而无需等待A。
有人知道怎么解决这个问题吗?
发布于 2020-04-09 11:33:56
尝试以下代码片段:
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)条件允许一些(有限的)可打印字符子集。根据键Enum…调整它
发布于 2020-04-09 11:58:29
以下这些是否弥补了人们的期望,
($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'"
}
}https://stackoverflow.com/questions/61117962
复制相似问题