简体   繁体   中英

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
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM