简体   繁体   中英

Start a program with WMIC and get its output

I am trying to run a program and get its PID so that I could terminate the program if it hung up during execution. I could not kill the program with program name since there will be more than one program running on the PC. I come across forums and got the suggestion of wmic usage but I could not get the output of the program with calling it with wmic.

It is about the same problem as mentioned in this post: Remote Netstat to STDOUT with WMIC?

I tried this command as suggested to execute the program and output:

   wmic process call create "cmd /C > C:\temp\test.txt 2>&1 netstat.exe -ano" 

With this command, I am able to retrieve the output of the program but then the program is actually called from another cmd? This defied the original purpose why I had initially trying to use wmic.

Anyone could tell if I have another way to do get the output or another way to call a program from batch, get its PID and the output redirection of the program called?

This an example from this question : How to capture the PID of a process when launching it in DOS ?

@echo off
rem there is a tab in the file at the end of the line below
set tab=    
set "cmd=cmd /k ^> C:\temp\test.txt 2^>^&1 netstat.exe -ano"
set dir=%~dp0

echo Starting MyProg
set pid=notfound

for /F "usebackq tokens=1,2 delims=;=%tab% " %%i in (
    `wmic process call create "%cmd%"^, "%dir%"`
) do (
    if %%j gtr 0 (
        set "pid=%%j"
    )
)
Call :Trim "%pid%"
echo MyPID = "%pid%"
echo Hit any key to kill the process created by WMIC 
pause>nul
Taskkill /F /PID %pid%
pause & exit
::*************************************************************************************
:Trim <String>
set "vbsfile=%tmp%\%~n0.vbs"
(
    echo Wscript.echo Trim("%~1"^)
)>"%vbsfile%"
for /f "delims=" %%a in ('Cscript /nologo "%vbsfile%"') do ( set "pid=%%a" )
If Exist "%vbsfile%" Del "%vbsfile%"
exit /b
::*************************************************************************************

since you only need the PID to kill the process, you could also use the windowtitle:

start "UniqueWindowTitle" cmd /c "ping /t google.de >out.txt 2>&1"
timeout /t 10
taskkill /fi "WINDOWTITLE eq UniqueWindowTitle" 2>nul
type out.txt

You could also add /min as start switch to not show the box.

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