有没有一种机制可以将击键发送到powershell进程?

问题描述 投票:0回答:1

我有一个必须在某种程度上进行交互的 CLI。我启动它,检查它的输出内容,然后根据它的输出内容发送“ENTER”。

在此处的 powershell 中进行设置已经相当复杂。从我正在使用的开始,


$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = "theCli.exe"
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$process = [System.Diagnostics.Process]::Start($processStartInfo)

一段时间后:

$output = $process.StandardOutput.ReadToEnd()
$matched = $output -match $pattern

if ($matched){
  # Send Key: Enter
}

我认为必须有一种方法可以做到这一点,即使我必须注入一个大型 C# 类型。我见过的一种替代方法是启动一个 shell,并使用 Windows 窗体将键发送到焦点下的窗口(另一个 shell)。这不好,因为用户将是我以外的人,他们会玩游戏 - 所以如果我不能在不使用 Windows 表单的情况下做到这一点,我将找到其他方法来获取信息比 CLI。或者,我们必须更改 CLI。

问题在于:虽然这可能很难或很难,但有没有办法将几个按键推送到没有 Windows 窗体托管的 powershell 子进程?更好的是,有没有办法将其推至

[System.Diagnostics.Process]

powershell
1个回答
0
投票

由于您正在处理 console 应用程序,因此您应该通过其 stdin(标准输入)流向其提供输入,而不是尝试模拟交互式用户输入。

虽然在程序运行时有条件地发送 stdin 输入以响应迄今为止收到的 stdout 输出并不简单,但实用的解决方案可能是无条件发送 stdin 输入,并在不需要时依赖它来忽略 .

以下示例说明了这一点:

# Effectively send ENTER (a newline) via stdin to respond to the `pause` prompt.
'' | cmd /c pause

# Do the same for a command that *doesn't* read from stdin, relying on it
# to be ignored.
'' | cmd /c ver
© www.soinside.com 2019 - 2024. All rights reserved.