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?)
The basic command syntax to forcefully kill a specific process is as follows: taskkill /PID process-number /F.
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.
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.
Try this for the if condition:
if (Get-Process "notepad" -ErrorAction SilentlyContinue | Where-Object {-not $_.HasExited })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With