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

PowerShell脚本开机启动时无法识别键盘按键问题咨询

问题描述

脚本功能为响应键盘F3、F4指令,在终端或CMD中直接运行时完全正常,但通过开机启动的CMD调用脚本时,脚本虽能运行却无法接收键盘指令。

开机启动命令行

powershell  -WindowStyle hidden -ExecutionPolicy Bypass C:\PowerShell\KeyBoardTest\Keyboard-Command-Response.ps1 >>  C:\PowerShell\KeyBoardTest\Keyboard-Command-Response_log.log

测试用PowerShell脚本

$shell = New-Object -ComObject "Shell.Application"
$Pause_script = 0
$exit_command = 'FALSE'

Sleep -Seconds 3
$Res= $shell.minimizeAll()

While ($exit_command -eq 'FALSE')
{
    Sleep -Seconds 1
    Write-Output "Mylog: Waiting to Keyboard"
    if ([Console]::KeyAvailable)
    {
        
        $KeyPressed = [System.Console]::ReadKey() 
        Write-Output "Mylog: Identified Press of key"
        switch ($KeyPressed.key)
        {
        F3 { 
            if ($Pause_script -eq 0){
                $Pause_script = 1
                Write-Output "Mylog: F3 Detected, Pausing Run"
                }
            else{
                $Pause_script = 0 
                Write-Output "Mylog: F3 Detected, Resuming Run"   
                }
            }
        F4 {
            $exit_time = Get-Date
            [DateTime]$Date = $exit_time
            $mytime = $date.ToShortDateString() + " " + $date.ToShortTimeString()
            Write-Output "Mylog: F4 Detected, Exiting the loop at: $mytime"
            $Exit_Command = 'TRUE'
            break
            }
        }
    }
}

终端正常运行时的日志(按下5次F3和1次F4)

Mylog: Waiting to Keyboard
Mylog: Waiting to Keyboard
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Resuming Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Resuming Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F3 Detected, Pausing Run
Mylog: Waiting to Keyboard
Mylog: Identified Press of key
Mylog: F4 Detected, Exiting the loop at: 7/23/2022 2:35 PM

差异原因分析

  • 控制台会话关联缺失:你使用-WindowStyle hidden参数启动PowerShell,导致进程运行在无可见控制台窗口的状态。脚本依赖的[Console]::KeyAvailable和[System.Console]::ReadKey()必须关联有效交互式控制台会话才能读取键盘输入,无控制台时这些API无法捕获任何键盘事件。
  • Session 0隔离机制:Windows开机启动的后台进程默认运行在Session 0系统级隔离会话中,该会话无用户交互界面,无法接收当前用户桌面会话(通常为Session 1及以上)的键盘输入。而手动在终端运行脚本时,进程处于用户的交互式会话,可直接获取键盘事件。
  • 输入流异常:启动命令用>>将输出重定向到日志文件,同时无控制台状态下,进程标准输入流未关联用户键盘设备,而是处于断开或指向空设备的状态,导致[Console]类无法读取输入。

内容的提问来源于stack exchange,提问作者Yaron

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:27:22