如何确保给定进程不运行,如果是,则终止脚本

Wil*_*nis 6 powershell

我有一个脚本,我停止(杀死)一个过程.紧接着,我想要一些代码检查进程是否确实停止了,如果没有,退出脚本(如果它确实停止了,脚本当然会继续.)这是我试图这样做的方法:

if (Get-Process "notepad" -ErrorAction SilentlyContinue) {
    Write-Host "Program still running somehow, terminating script..."
    exit
}
else
{ Write-Host "Program stopped." }
Run Code Online (Sandbox Code Playgroud)

我以为我已经弄清楚(Get-Process "progname" -ErrorAction SilentlyContinue)如果有一个或多个进程正在运行(即返回输出),语句将eval为$ true,如果没有返回输出则返回$ false(我指定了-ErrorAction SilentlyContinue以确保没有输出)当没有找到该名称的程序时返回输出.)当我使用正在运行的程序(例如"notepad")运行此代码块时,以及当我尝试使用不存在的程序时(例如"notepadxxx") ".)

但是,当我将它集成到我的大型程序中时,将其放在终止程序的行之后,如下:

Write-Host "Terminating Program..."
Stop-Process -Name "notepad" -Force
if (Get-Process "notepad" -ErrorAction SilentlyContinue) {
    Write-Host "Program still running somehow, terminating script..."
    exit
}
else
{ Write-Host "Program stopped." }
Run Code Online (Sandbox Code Playgroud)

Get-Process行逃避$ true,并结束脚本.这只是Stop-Process线路和后续Get-Process线路之间的竞争条件,还是逻辑缺陷?(如果是的话,有什么问题?)

man*_*lds 3

尝试一下 if 条件:

if (Get-Process "notepad" -ErrorAction SilentlyContinue | Where-Object {-not $_.HasExited }) 
Run Code Online (Sandbox Code Playgroud)