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

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

一、ps1脚本

文件名:KeyboardCheck.ps1
  1. Function WaitForKeyPress($TimeoutInSeconds) {
  2.     $KeyPressed = $false
  3.     $deadline = (Get-Date).AddSeconds($TimeoutInSeconds)
  4.    
  5.     # 显示提示信息
  6.     Write-Host "请在 $TimeoutInSeconds 秒内按下任意键(长时间没有检测到按下按键会被认为键盘可能有问题)" -ForegroundColor Blue
  7.     # 使用 ReadKey 和 Sleep 来实现等待
  8.     while ((Get-Date) -lt $deadline -and !$KeyPressed) {
  9.         if ([Console]::KeyAvailable) {
  10.             # 按键被按下了
  11.             $key = [Console]::ReadKey($true)  # $true 表示不显示按键
  12.             Write-Host "检测到按键 '$($key.KeyChar)' ($($key.Key))" -ForegroundColor Green
  13.             $KeyPressed = $true
  14.         } else {
  15.             Start-Sleep -Milliseconds 100  # 延迟 100 毫秒
  16.         }
  17.     }
  18.     if ($KeyPressed) {
  19.         Write-Host "在 $TimeoutInSeconds 秒内按下了按键。"
  20.     } else {
  21.         Write-Host "$TimeoutInSeconds 秒内没有按键!你的键盘可能有问题!" -ForegroundColor Red
  22.     }
  23.     # 返回是否检测到按键的值
  24.     return $KeyPressed
  25. }
  26. Function ExitWithCountdown {
  27.     param (
  28.         [int]$Seconds = 10  # 默认倒计时时间为10秒
  29.     )
  30.     Write-Host
  31.     Write-Host "脚本将在 $Seconds 秒后自动关闭窗口" -ForegroundColor Magenta
  32.     for ($i = $Seconds; $i -gt 0; $i--) {
  33.         Write-Host -NoNewline "`r正在退出... {$i}秒后关闭窗口..."
  34.         Start-Sleep -Seconds 1
  35.     }
  36. }
  37. # 获取5秒内是否按下了任意键
  38. $IsKeyPressed = WaitForKeyPress -TimeoutInSeconds 5
  39. # 根据 $IsKeyPressed 的值调用 cmd.exe
  40. if ($IsKeyPressed) {
  41.     Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_t" -NoNewWindow -Wait
  42. } else {
  43.     Start-Process -FilePath "cmd.exe" -ArgumentList "/c echo cmd_f" -NoNewWindow -Wait
  44. }
  45. # 延迟退出
  46. ExitWithCountdown
复制代码
二、开机自启动

打开路径:%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
将下面的代码保存到名为start_KeyboardCheck.bat的文件中
(代码中的文件路径自行修改)
  1. @echo off
  2. echo.
  3. echo ScriptPath:%~dp0
  4. set "ps1Path=C:\MyScript\KeyboardCheck.ps1"
  5. if exist "%ps1Path%" (
  6.     echo File "%ps1Path%" exists
  7.     PowerShell -NoLogo -ExecutionPolicy Bypass -File "%ps1Path%"
  8. ) else (
  9.     echo File "%ps1Path%" does not exist, please check the path!
  10.     pause
  11. )
复制代码
三、效果


四、有什么用

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

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

玛卡巴卡的卡巴卡玛

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表