3
votes

I'm working on a batch file that is supposed to START a process (CMD) and then it should kill the process after finished. Problem is, that Imagename is cmd.exe and the other problem is that it should be running on Jenkins. This is what I have tested:

  • Getting PID with wmic using name of window to find process -> Failed at Jenkins
  • Taskkill by naming the window-> Failed because Jenkins does not display windows due to security issues.
  • Taskkill by imagename -> Failed because there are other cmd processes running at the same time
  • Taskkill with pid but pid from the last cmd started. -Works but it is not very safe.

I couldn´t understand how wmic works but as I see, I cannot start a process with a command like with START command.

Conditions:

  • It can't be kill after some time because I need the output from the mergetool and sometimes mergetool can take too long.

  • It should run at same time with other (cmd) processes // Jenkins

My question, is there a way of getting the PID from the START Command?

Here are some questions that helped me a lot! Windows batch file : PID of last process? Compare number of a specific process to a number

CODE:

set "console_name=cmd.exe"
set "git_command=%gitcmd% mergetool ^>output.txt"
tasklist /FI "imagename eq %console_name%" /NH /FO csv > task-before.txt
START "mergetool_w" CMD /c %git_command%
tasklist /FI "imagename eq %console_name%" /NH /FO csv > task-after.txt
for /f "delims=, tokens=2,*" %%A in ('fc /L /LB1  task-before.txt task-after.txt') do set pid=%%A
pid=!pid:"=!
echo pid is %pid%
TASKKILL /t /pid %pid% /f
2

2 Answers

1
votes

You could actually use findstr for checking what tasks have been added after your start command line, relying on your files task-before.txt and task-after.txt:

findstr /LXVG:task-before.txt task-after.txt

Due to a nasty bug, this might under some circumstances lead to an unexpected output. To prevent that, add the /I option, if you can live with case-insensitive searches:

findstr /ILXVG:task-before.txt task-after.txt
0
votes

Yes it's very possible. I'm going to take code from my previous awnser on another post here: Stop Execution of Batch File after 20 Seconds and move to Next

I want to first assume "mergetool_w" is the name of the CMD you are opining with the start...

The way you want to go about this is to search the tasklist for your console title and extract the PID# out of the context. The find suffix can be used to "Filter" the results along with tokens=2 to extract only the PID#.

FOR /F "tokens=2" %%# in ('tasklist /v ^| find "mergetool_w"') do set PID=%%#

From there, you can now kill this new window using the taskkill /pid command. The PID# is stored in the string %PID% so the command is simple:

taskkill /pid %PID% /t /f

Finaly, it looks as if you are trying to "Log" the data so feel free to put > text-task.txt where it's needed.