【问题标题】:Press any key to continue [duplicate]按任意键继续[重复]
【发布时间】:2015-04-30 06:33:56
【问题描述】:

根据微软的documentationread-host 让用户键入一些输入,然后按回车键继续。如果您想要“按任意键继续”,则不完全是正确的行为。 (等等... Any 键在哪里?!)

有没有办法做到这一点? read-char 之类的东西?

我尝试搜索“单字符输入”和“powershell 输入”,看看能否找到所有输入方式的列表,但运气不佳。还有几个看起来很有希望的 Stack Overflow 问题使用 read-host,它实际上不适用于“按任意键...”功能。

【问题讨论】:

  • 好旧的powershell tip of the week(通过搜索 Powershell 和 Pause 找到,pause 是命令提示符/MS dos 中显示该文本的命令)

标签: powershell


【解决方案1】:

这是我使用的。

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

【讨论】:

  • 我收到一个错误:Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented." At C:\file.ps1:26 char:5 + $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown'); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : NotImplementedException
  • @gakera 这在 Powershell ISE 下不起作用。
  • 请查看 (Jerry G) 的答案,了解如何修复 ISE。这些问题是导致我提出这个问题的原因
  • 从 PowerShell 命令运行脚本时可以正常工作。
【解决方案2】:

我创建了一个小的 Powershell 函数来模拟 MSDOS pause。这处理是否运行 Powershell ISE 或非 ISE。 (ReadKey not 在 powershell ISE 中工作)。运行 Powershell ISE 时,此函数会打开一个 Windows MessageBox。这有时会令人困惑,因为MessageBox 并不总是出现在最前面。不管怎样,就这样吧:

用法: pause "Press any key to continue"

函数定义:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

【讨论】:

  • 在 VSCode 中不起作用
  • $message ="Press any key to continue" pause ($message) 对我来说它在 ise 和 powershell 中工作,我只添加了这行,也许你需要在 vs 代码中做同样的事情?! @ZaxLofful
【解决方案3】:

查看System.Console .NET 类的ReadKey() 方法。我认为这会满足您的需求。

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

例子:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

【讨论】:

  • 这仅适用于 powershell.exe - 它不适用于 ISE 等图形主机。
  • 对漂亮和简单投赞成票。
猜你喜欢
  • 2020-08-10
  • 2013-11-10
  • 2015-01-23
  • 1970-01-01
  • 2011-12-13
  • 2010-11-29
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多