PowerShell中Wait-Process并发等待多进程的实现问题
解决PowerShell进程监控阻塞问题
你的问题出在Wait-Process的阻塞特性上:当代码执行到Wait-Process时,会暂停当前线程,直到目标进程关闭才会继续往下运行。所以如果两个进程同时运行,代码只会先处理第一个检测到的进程,完全没法同时监控两个进程的状态变化。
下面是修改后的代码,用**后台作业(Start-Job)**实现并行监控,这样两个进程的状态变化会被独立追踪,不会互相阻塞:
# 定义监控单个进程的函数 function Monitor-Process { param( [string]$ProcessName, [string]$OpenMessage, [string]$CloseMessage ) do { # 等待进程启动 $process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue while (-not $process) { Start-Sleep -Seconds 1 $process = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue } # 发送进程启动通知 Show-Notification -ToastTitle $OpenMessage # 等待进程关闭 Wait-Process -Id $process.Id # 发送进程关闭通知 Show-Notification -ToastTitle $CloseMessage } while ($true) } # 启动两个后台作业,分别监控计算器和任务管理器 Start-Job -ScriptBlock ${function:Monitor-Process} -ArgumentList 'Calculator', 'Calculator is open.', 'Calculator is closed.' | Out-Null Start-Job -ScriptBlock ${function:Monitor-Process} -ArgumentList 'Taskmgr', 'Taskmgr is open.', 'Taskmgr is closed.' | Out-Null # 保持主脚本运行,定期清理已完成的作业 do { Start-Sleep -Seconds 5 Get-Job -State Completed | Remove-Job } while ($true)
代码说明:
Monitor-Process函数:封装了单个进程的完整监控逻辑——先等待进程启动,发送启动通知;再等待进程关闭,发送关闭通知,之后循环重复这个流程。Start-Job:把每个进程的监控任务放到独立的后台作业中运行,两个任务并行执行,不会互相阻塞。- 主循环:保持脚本运行,同时定期清理已完成的后台作业,避免资源占用。
如果需要停止所有监控,执行Get-Job | Stop-Job | Remove-Job即可终止并清理所有后台作业。
内容的提问来源于stack exchange,提问作者knight Smoke
相关产品推荐
相关产品推荐

