Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that a given process is NOT running, & terminate script if it is

Tags:

powershell

I have a script wherein I stop (kill) a process. Immediately thereafter, I'd like some code to check if the process is indeed stopped, and if not, exit the script (and if it indeed is stopped, the script will of course continue.) Here's how I tried to do it:

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

I thought I had it figured out that the statement (Get-Process "progname" -ErrorAction SilentlyContinue) would eval to $true if there was one or more processes running (i.e. there was output returned), and $false if no output was returned (I specified the -ErrorAction SilentlyContinue to make sure there would be no output returned when there was not program found by that name.) It worked in testing when I ran this code block using a running program (say, "notepad"), and also when I tried a non-existant program (like say "notepadxxx".)

However, when I then integrated it into my larger program, and put it immediately after the line which terminates the program, as so:

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 line evals to $true, and ends the script. Is this just a race condition between the Stop-Process line, and the subsequent Get-Process line, or is it a logic flaw? (and if so, what's the fix?)

like image 750
Will Dennis Avatar asked Jul 25 '13 19:07

Will Dennis


People also ask

How do I stop a Process in PowerShell?

The basic command syntax to forcefully kill a specific process is as follows: taskkill /PID process-number /F.

How do you check if Process is running in Windows using PowerShell?

With a PowerShell console open, run Get-Process using the Name parameter to only show all running processes with Calculator as the name. You'll see the same output you've seen previously. Get-Process returns many properties as expected.

What is the PowerShell command for returning a list of PowerShell processes running on your computer?

If you have been using Windows PowerShell for a while, then you are probably familiar with the Get-Process cmdlet. This cmdlet, which you can see in Figure 1, returns a list of the various processes that are running on your computer.


1 Answers

Try this for the if condition:

if (Get-Process "notepad" -ErrorAction SilentlyContinue | Where-Object {-not $_.HasExited }) 
like image 120
manojlds Avatar answered Oct 13 '22 11:10

manojlds