I'm looking for something like chp.exe, it can runs a command and returns its pid. I can not use CHP.EXE because it seems to be reported as infected file in some antiviruses.
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.Sign up to join this community
Wmic process where (Name like '%CHP%') get caption, name, commandline, ProcessId | more
Wmic process where (Name like '%ie%') get caption, name, commandline, ProcessId | more
Wmic process get ProcessId
extract only the processId into a variable from query output:
@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%
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.
Another way :: You can create a batch file and put following code to batch file. Its first run netstat command to get processId for port 9797. And then set it into a variable.
@ECHO OFF FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "9797" ') DO ( SET /A ProcessId=%%T) &GOTO SkipLine :SkipLine echo ProcessId = %ProcessId% PAUSE
You can run the program and then issue this command, substituting
firefox.exe with the process name you want:
for /f "tokens=2" %a in ('tasklist /nh /fi "imagename eq firefox.exe"') do @if not [%a]==[No] @echo %a
It will output solely the pid. In my case, the output is
5540. If the program is not running, no output will be returned.