如何让PowerShell脚本自动定时刷新进程列表无需手动输入?
解决PowerShell脚本自动刷新进程列表并支持非阻塞输入的问题
原脚本的核心问题是Read-Host属于阻塞式命令,会强制暂停脚本执行直到用户完成输入,导致无法实现定时自动刷新进程列表的需求。要达成每10秒自动刷新、同时支持随时输入PID终止进程的效果,需要改用非阻塞的输入检测逻辑,修改后的脚本如下:
while($true){ # 清屏并刷新显示shell进程列表 Clear-Host Get-Process | Where-Object {$_.ProcessName -match "cmd|powershell|bash"} | Format-Table Name,Id,StartTime Write-Host "`nWhat shell would you like to kill(Id)? Your shell=$PID (输入数字ID后回车,或等待10秒自动刷新)" $refreshInterval = 10 # 自动刷新间隔(秒) $startTimestamp = Get-Date $hasInput = $false $targetId = $null # 在超时窗口内监听用户输入,不阻塞脚本执行 while ((Get-Date) - $startTimestamp -lt (New-TimeSpan -Seconds $refreshInterval)) { if ($host.UI.RawUI.KeyAvailable) { $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $inputBuffer = @() # 读取完整输入直到回车,仅允许数字输入并处理退格 while ($key.Key -ne "Enter") { if ($key.Key -eq "Backspace" -and $inputBuffer.Count -gt 0) { $inputBuffer = $inputBuffer[0..($inputBuffer.Count-2)] Write-Host "`b `b" -NoNewline } elseif ($key.KeyChar -match '\d') { $inputBuffer += $key.KeyChar Write-Host $key.KeyChar -NoNewline } $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") } $targetId = -join $inputBuffer $hasInput = $true break } Start-Sleep -Milliseconds 100 # 降低CPU占用率 } # 若输入有效则执行进程终止操作 if ($hasInput -and $targetId -match '^\d+$') { Stop-Process -Id $targetId -Force -ErrorAction SilentlyContinue Write-Host "`n已尝试终止进程ID $targetId" Start-Sleep -Seconds 1 } }
关键逻辑说明
- 用
$host.UI.RawUI.KeyAvailable实现非阻塞输入检测,避免脚本被强制暂停 - 设置10秒超时窗口,到时间自动进入下一次循环刷新进程列表
- 限制输入仅为数字(匹配进程ID格式),并处理退格键的显示回退
- 仅当输入有效数字时才执行进程终止操作,避免无效输入报错
内容的提问来源于stack exchange,提问作者Chips McCoy
相关产品推荐
相关产品推荐

