Run a process and return its PID (as CHP.EXE) for a batch file

Wmic process where (Name like '%CHP%') get caption, name, commandline, ProcessId | more

real sample:

Wmic process where (Name like '%ie%') get caption, name, commandline, ProcessId | more

Output:

ProcessId where like name Wmic Far manager

Wmic process get ProcessId

extract only the processId into a variable from query output:

ProcID.cmd:

@ECHO OFF                                                                              
FOR /F %%T IN ('Wmic process where^(Name^="explorer.exe"^)get ProcessId^|more +1') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo ProcessId = %ProcessId%                                                           

Output:

ProcessId = 2372    

This is pretty straightforward to do in PowerShell. Start-Process notepad.exe -PassThru will start Notepad and return:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                                                              
-------  ------    -----      ----- -----   ------     -- -----------                                                                                                                              
     45       6     1672       4240    61     0.02   9212 notepad   

From there you could use it like an object by storing the output ($notepad = Start-process notepad.exe -PassThru and then $notepad.ID) and finish whatever scripting you were doing with it.

Getting it back to a batch script (if absolutely necessary) is a little tricky. If you're absolutely stuck on using a batch file, it would probably be easiest to write a PowerShell script that writes the relevant information to a file or registry key, call the PowerShell script from the batch file, and then read the file or reg key later in the batch script.

If you don't want to touch PowerShell at all then you'll have to resort to WMIC or tasklist to find the process after creating it.

Tags:

Pid

Batch