首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell ReadKey()区分大小写

Powershell ReadKey()区分大小写
EN

Stack Overflow用户
提问于 2020-04-09 09:28:39
回答 2查看 410关注 0票数 1

在我的脚本中,我需要从用户那里获得一个字符,并且在没有等待进入的情况下立即处理它。此外,我想处理字符区分大小写。

代码语言:javascript
复制
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。

有人知道怎么解决这个问题吗?

EN

回答 2

Stack Overflow用户

发布于 2020-04-09 11:33:56

尝试以下代码片段:

代码语言:javascript
复制
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…调整它

票数 1
EN

Stack Overflow用户

发布于 2020-04-09 11:58:29

以下这些是否弥补了人们的期望,

代码语言:javascript
复制
($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'"
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61117962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档