判断按键盘是否好使的开机自启动PowerShell脚本

一、ps1脚本

文件名:KeyboardCheck.ps1

powershell 复制代码
Function WaitForKeyPress($TimeoutInSeconds) {
    $KeyPressed = $false
    $deadline = (Get-Date).AddSeconds($TimeoutInSeconds)
    
    # 显示提示信息
    Write-Host "请在 $TimeoutInSeconds 秒内按下任意键(长时间没有检测到按下按键会被认为键盘可能有问题)" -ForegroundColor Blue

    # 使用 ReadKey 和 Sleep 来实现等待
    while ((Get-Date) -lt $deadline -and !$KeyPressed) {
        if ([Console]::KeyAvailable) {
            # 按键被按下了
            $key = [Console]::ReadKey($true)  # $true 表示不显示按键
            Write-Host "检测到按键 '$($key.KeyChar)' ($($key.Key))" -ForegroundColor Green
            $KeyPressed = $true
        } else {
            Start-Sleep -Milliseconds 100  # 延迟 100 毫秒
        }
    }

    if ($KeyPressed) {
        Write-Host "在 $TimeoutInSeconds 秒内按下了按键。"
    } else {
        Write-Host "$TimeoutInSeconds 秒内没有按键!你的键盘可能有问题!" -ForegroundColor Red
    }

    # 返回是否检测到按键的值
    return $KeyPressed
}

Function ExitWithCountdown {
    param (
        [int]$Seconds = 10  # 默认倒计时时间为10秒
    )

    Write-Host
    Write-Host "脚本将在 $Seconds 秒后自动关闭窗口" -ForegroundColor Magenta
    for ($i = $Seconds; $i -gt 0; $i--) {
        Write-Host -NoNewline "`r正在退出... {$i}秒后关闭窗口..."
        Start-Sleep -Seconds 1
    }
}

# 获取5秒内是否按下了任意键
$IsKeyPressed = WaitForKeyPress -TimeoutInSeconds 5

# 根据 $IsKeyPressed 的值调用 cmd.exe
if ($IsKeyPressed) {
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_t" -NoNewWindow -Wait
} else {
    Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_f" -NoNewWindow -Wait
}

# 延迟退出
ExitWithCountdown

二、开机自启动

打开路径:%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup

将下面的代码保存到名为start_KeyboardCheck.bat的文件中

(代码中的文件路径自行修改)

bash 复制代码
@echo off

echo.
echo ScriptPath:%~dp0

set "ps1Path=C:\MyScript\KeyboardCheck.ps1"

if exist "%ps1Path%" (
    echo File "%ps1Path%" exists
    PowerShell -NoLogo -ExecutionPolicy Bypass -File "%ps1Path%"
) else (
    echo File "%ps1Path%" does not exist, please check the path!
    pause
)

三、效果

四、有什么用

额*****,没啥用,配合这个知乎贴如何禁用笔记本自带键盘?,免得真的没键盘用😓

相关推荐
ACP广源盛1392462567320 分钟前
iOS 27 开放 AI 生态@ACP#小型化扩展黄金风口,IX8008全面超越 ASM2806,铸就嵌入式 AI 扩展核心
人工智能·嵌入式硬件·macos·ios·计算机外设·objective-c·cocoa
Jwest20214 小时前
工业显示器什么牌子质量最好性价比最高?
计算机外设
hudawei99611 小时前
RK R87 Pro AI键盘,AI功能设置与连接教程
人工智能·计算机外设·使用说明·rk r87 ai键盘
console.log('npc')14 小时前
Windows 11 安装 WSL2 + Ubuntu + Docker + Codex + Sub2API 教学
windows·docker·powershell·ubantu·codex
byte轻骑兵1 天前
【HID】规范精讲[16]: 蓝牙键盘默认状态玄机——连接中断后,那些设置为何会重置?
人工智能·计算机外设·人机交互·蓝牙键盘·蓝牙鼠标
代码对我眨眼睛1 天前
Mac 如何单独修改鼠标滚动方向,而不影响触控板
macos·计算机外设·策略模式
兴通物联科技1 天前
工业手持终端 PDA 键盘化设计与现场作业效率优化 —— 以 XT8001D 为例
大数据·物联网·计算机视觉·计算机外设·硬件架构
XTIOT6661 天前
工业数据采集设备选型 —— 实体键盘 PDA 的技术优势与场景适配(基于 XT8001D 实践)摘要
大数据·嵌入式硬件·物联网·计算机外设
CV工程师(Ctrl)1 天前
Codex 在 Windows 中文路径执行bash命令编码问题复盘
powershell·codex
脑瓜嗡1 天前
AutoHotkey按下方向键将鼠标左键按住向上滑动
计算机外设