I have a script in which I stop (kill) a process. Right after that, I would like some code to check if the process is really stopped, and if not, exit the script (and if it really is stopped, then of course there will be a script). Here, as I tried to do this:
if (Get-Process "notepad" -ErrorAction SilentlyContinue) { Write-Host "Program still running somehow, terminating script..." exit } else { Write-Host "Program stopped." }
It seemed to me that I realized that the expression (Get-Process "progname" -ErrorAction SilentlyContinue) would be true if one or more processes were started (i.e. the result was returned) and $ false if the result was not returned (I pointed out -ErrorAction SilentlyContinue to make sure that the result will not be returned when there was no program found by this name.) It worked during testing when I ran this block of code using a running program (say, notepad), and also when I tried a nonexistent program (for example, "notepadxxx".)
However, when I then integrated it into my larger program and placed it immediately after the line that ends the program, like this:
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." }
the Get-Process points to $ true and ends the script. Is it just a race condition between the Stop-Process line and the subsequent Get-Process , or is it a logical flaw? (and if so, what is the fix?)
source share