使用英语阅读

通过


about_PSConsoleHostReadLine

简短说明

说明如何在控制台提示符下自定义 PowerShell 如何读取输入。

长说明

从 Windows PowerShell 3.0 开始,可以编写一个名为 PSConsoleHostReadLine 的函数,该函数替代处理控制台输入的默认方式。

此函数由 PSReadLine 模块扩展。

例子

以下示例启动记事本并从用户创建的文本文件获取输入:

PowerShell
function PSConsoleHostReadLine {
  $inputFile = Join-Path $env:TEMP PSConsoleHostReadLine
  Set-Content $inputFile "PS > "

  # Notepad opens. Enter your command in it, save the file, and then exit.
  notepad $inputFile | Out-Null
  $userInput = Get-Content $inputFile
  $resultingCommand = $userInput.Replace("PS >", "")
  $resultingCommand
}

言论

默认情况下,PowerShell 在所谓的“处理模式”中从控制台读取输入 -- 在这种模式下,Windows 控制台子系统处理所有按键、F7 菜单和其他输入。 当您按下 进入选项卡, PowerShell 会获取您在此之前输入的文本。 在按下 Enter 或 +之前,无法检测到你是否按了 Ctrl+、Ctrl+、CtrlE或任何其他键。在 Windows PowerShell 3.0 中,PSConsoleHostReadLine 函数解决了这个问题。 在 PowerShell 控制台主机中定义名为 PSConsoleHostReadline 的函数时,PowerShell 将调用该函数,而不是“烹饪模式”输入机制。

另请参阅