javawindowscmd

Get the own process pid from the command prompt in windows


I'm trying to get the PID from command prompt of its own. But when using the below command i'm not getting the desired output always. Can you please point out what was the error in the below statement?

cmd.exe /c title="mycmd" & tasklist /v /fo csv | findstr /i "mycmd" & dir & help

Edit:

The below command working correctly. But when combine it with two more commands. It's not working.

cmd.exe /c title="mycmd" & tasklist /v /fo csv | findstr /i "mycmd"

Additional Info:

I'm using Java

final List<String> commands = new ArrayList<String>();                

commands.add("cmd.exe");
commands.add("/C");

//.. Add more commands

ProcessBuilder pb = new ProcessBuilder(commands);

Solution

  • You can get the PID of the cmd prompt using below batch file.

    Reference: http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/270f0842-963d-4ed9-b27d-27957628004c/

    GetPID.bat

    @echo off
    if not defined SESSIONNAME set SESSIONNAME=Console
    setlocal
    set instance=%DATE% %TIME% %RANDOM%
    title %instance%
    for /f "usebackq tokens=2" %%a in (`tasklist /FO list /FI "SESSIONNAME eq %SESSIONNAME%" /FI "USERNAME eq %USERNAME%" /FI "WINDOWTITLE eq %instance%" ^| find /i "PID:"`)
        do set PID=%%a
    if not defined PID for /f "usebackq tokens=2" %%a in (`tasklist /FO list /FI "SESSIONNAME eq %SESSIONNAME%" /FI "USERNAME eq %USERNAME%" /FI "WINDOWTITLE eq Administrator:  %instance%" ^| find /i "PID:"`)
        do set PID=%%a
    if not defined PID
     echo !Error: Could not determine the Process ID of the current script.  Exiting.& exit /b 1
    echo PID: "%PID%"