Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait and kill a timeout process in Powershell

Using Powershell 2.0 in a Windows 7 desktop

I want to create a process to run an ant command, and then wait for that process to finish in several minutes. If time out and the process still running then I want to kill it.

I have wrote some code as below:

$p = Start-Process "cmd.exe" '/c ant execute' -PassThru -RedirectStandardOutput $log_file_path
Wait-Process -id $p.ID -timeout 100
if(!$p.hasExited) {
    echo "kill the process"
    $p.Kill()
    #Stop-Process $p.ID
}

Start-Sleep -s 30

# continue to do other things

Although the process didn't get killed, it's still running even after the Start-Sleep statement get executed.

I also tried with Stop-Process command, as the commented out line indicates, no luck, the process still running.

I may have missed something important, please give a clue.

EDIT :

It turns out there are some child processes still running in the cmd window, kill only the cmd process is not enough.

I finally get the job done with following code:

if(!$p.hasExited) {
    echo "kill the process"
    taskkill /T /F /PID $p.ID
    #$p.Kill()
    #Stop-Process $p.ID
}
like image 824
poiu2000 Avatar asked Oct 23 '13 04:10

poiu2000


People also ask

How do you kill a process in PowerShell?

At the command line, you can terminate a Windows process with the command taskkill. In order to use this command, you need to know its process ID (PID). You can get a list of all running tasks with the command tasklist. Once you know the PID, use the taskkill command in this manner: taskkill /PID <PID> /F.

Is there a Wait command in PowerShell?

The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process .


2 Answers

If you want to kill the entire process tree, you need to also find and stop the child processes.

Here's a good article that explains it and shows you how to do that:

http://powershell.com/cs/blogs/tobias/archive/2012/05/09/managing-child-processes.aspx

like image 101
mjolinor Avatar answered Oct 01 '22 06:10

mjolinor


I pushed in github tiny project which can be used to run process and setup timeout for him and for his child proccesses: https://github.com/burlachenkok/process_tool

It's a sources with Makefile, and it's not a powershell script. But hope it can be usefull for you.

like image 40
Konstantin Burlachenko Avatar answered Oct 01 '22 07:10

Konstantin Burlachenko