You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PowerShell脚本等待CMD窗口显示指定文本后再发送回车?

解决PowerShell等待CMD提示后自动发送回车的问题

你当前的代码用固定延迟等待,无法适配网络加载慢的场景,可通过检测CMD窗口的提示文本来实现精准触发回车,具体方案如下:

实现思路

  • 调用Windows原生API获取CMD窗口的句柄及内容
  • 循环检测窗口文本,直到出现目标提示press any key to continue
  • 检测到提示后自动发送回车按键

完整代码

# 导入Win32 API用于获取窗口信息
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowHelper {
    // 查找窗口(按类名,CMD窗口类名为ConsoleWindowClass)
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    // 获取窗口所属进程ID
    [DllImport("user32.dll")]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    
    // 获取窗口文本长度
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern int GetWindowTextLength(IntPtr hWnd);
    
    // 获取窗口文本内容
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
}
"@

# 启动CMD并执行目标脚本,保留进程实例
$targetProcess = Start-Process cmd.exe -ArgumentList "/c M:\loc\to\file.cmd" -PassThru

# 等待CMD窗口创建,避免直接查找失败
Start-Sleep -Seconds 1

# 查找属于目标进程的CMD窗口句柄
$cmdWindowHandle = $null
while (-not $cmdWindowHandle) {
    # 查找所有CMD窗口
    $tempHandle = [WindowHelper]::FindWindow("ConsoleWindowClass", $null)
    if ($tempHandle) {
        # 验证窗口是否属于当前启动的进程
        $windowProcId = 0
        [WindowHelper]::GetWindowThreadProcessId($tempHandle, [ref]$windowProcId)
        if ($windowProcId -eq $targetProcess.Id) {
            $cmdWindowHandle = $tempHandle
        }
    }
    Start-Sleep -Milliseconds 300
}

# 循环检测窗口文本,直到出现目标提示
$targetPrompt = "press any key to continue"
$promptFound = $false
while (-not $promptFound) {
    $textLength = [WindowHelper]::GetWindowTextLength($cmdWindowHandle)
    if ($textLength -gt 0) {
        $textBuffer = New-Object System.Text.StringBuilder ($textLength + 1)
        [WindowHelper]::GetWindowText($cmdWindowHandle, $textBuffer, $textBuffer.Capacity)
        $windowContent = $textBuffer.ToString()
        
        # 检查是否包含目标提示
        if ($windowContent -match [regex]::Escape($targetPrompt)) {
            $promptFound = $true
        }
    }
    Start-Sleep -Milliseconds 300
}

# 发送回车按键
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

代码说明

  • 窗口句柄匹配:通过进程ID关联窗口,避免误操作其他打开的CMD窗口
  • 文本检测循环:每300毫秒检查一次窗口内容,直到找到目标提示
  • 按键发送:使用SendWait确保按键被目标窗口接收

内容的提问来源于stack exchange,提问作者RC-IT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 01:15:39