How to make sure that this process is NOT running, and exit the script if it

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?)

+6
source share
2 answers

Try this for the if condition:

 if (Get-Process "notepad" -ErrorAction SilentlyContinue | Where-Object {-not $_.HasExited }) 
+3
source

I think the problem is that you check immediately too. The if statement is executed before the process can stop. When you use the Stop-Process , it sends a stop signal to the command and moves on, it does not wait for the process to complete. Try adding Sleep 1 or even Sleep .1 between Stop-Process [...] and if (Get-Process [...] . Give it a moment to stop working before checking to see if it happened.

0
source

Source: https://habr.com/ru/post/950300/


All Articles