按任意键继续

根据微软的 documentationread-host允许用户输入一些输入,然后按回车继续。如果您希望“按任意键继续”,那么这种行为并不完全正确。(等等... Any的钥匙在哪里? !)

有没有办法做到这一点? 像 read-char

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

239035 次浏览

查看 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());

Here is what I use.

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

我已经创建了一个小的 Powershell 函数来模拟 MSDOS pause。这将处理是否运行 Powershell ISE 或非 ISE。(ReadKey在 Powershell ISE 中支持 没有)。当运行 Powershell ISE 时,此函数将打开一个 WindowsMessageBox。这有时可能会令人困惑,因为 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")
}
}