Detecting Process ID of the current cmd.exe

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Detecting Process ID of the current cmd.exe

#16 Post by Aacini » 21 Dec 2014 22:53

The solution below uses the new wmiCollection "data generating" function of FindRepl.bat version 2.2 that gives the same results of WMIC command, but run faster and works for any user. In this method FindRepl program generate the command lines of active processes and search for the same parameters used in its own execution, so this solution would only fail if this same program is executed two (or more) times at the exact same time. This point would require that two instances of FindRepl.bat program keep running in the same time interval, that is about 150 milliseconds in my not-so-fast computer.

Code: Select all

@echo off
setlocal

set "source=wmiCollection('Win32_Process','CommandLine','ParentProcessID')"
set "search=%source:(=\(%"
set "search=%search:)=\)%"

for /F "usebackq tokens=4 delims=," %%a in (`FindRepl "/S:%source%" =search /J`) do set "PID=%%~a" & goto continue
:continue
echo %PID%

Antonio

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Detecting Process ID of the current cmd.exe

#17 Post by dbenham » 21 Dec 2014 23:48

@Aacini - I can't get it to work. No error, is generated, it just prints ECHO is Off.

I made a copy of the FINDREPL command and CALLed it prior to the FOR /F.

Code: Select all

call FindRepl "/S:%source%" =search /J

It printed the following:

Code: Select all

wmiCollection('Win32_Process','CommandLine','ParentProcessID')


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Detecting Process ID of the current cmd.exe

#18 Post by foxidrive » 21 Dec 2014 23:52

It works here, Dave.

When I launch the for tail then I get this:

"CScript //nologo //E:JScript "c:\Files\bat\findrepl.bat" "/S:wmiCollection('Win32_Process','CommandLine','ParentProcessID')" =search /J","7248"

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Detecting Process ID of the current cmd.exe

#19 Post by Aacini » 22 Dec 2014 00:01

Do you have the last version of FindRepl? I just downloaded it from this site and tested it:

Code: Select all

C:\ type test.bat
@echo off
setlocal

set "source=wmiCollection('Win32_Process','CommandLine','ParentProcessID')"
set "search=%source:(=\(%"
set "search=%search:)=\)%"

for /F "usebackq tokens=4 delims=," %%a in (`FindRepl "/S:%source%" =search /J`
 do set "PID=%%~a" & goto continue
:continue
echo %PID%

C:\ test
13184

C:\ tasklist | findstr "cmd.exe"
cmd.exe                      13184 Console                    1     3,520 KB

Antonio

npocmaka_
Posts: 516
Joined: 24 Jun 2013 17:10
Location: Bulgaria
Contact:

Re: Detecting Process ID of the current cmd.exe

#20 Post by npocmaka_ » 22 Dec 2014 01:09

One more way using jscript.net (should be more portable than the powershell as Vista,XP,Win2003,Win2008 does not have powershell by default ). It again uses WMI classes (Win32_Process) but it was the easiest example that I could port from C# to jscript (e.g. it's impossible to use PInvoke from jscript) . I've used this example : http://stackoverflow.com/questions/2531 ... pplication



Code: Select all

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)


if not exist "%~n0.exe" (
   "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

%~n0.exe

endlocal & exit /b %errorlevel%

*/


import  System;
import  System.Diagnostics;
import  System.ComponentModel;
import  System.Management;

var myId = Process.GetCurrentProcess().Id;
var query = String.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
if (!results.MoveNext()) {
   Console.WriteLine("Error");
   Environment.Exit(-1);
}
var queryObj = results.Current;
var parentId = queryObj["ParentProcessId"];
var parent = Process.GetProcessById(parentId);
Console.WriteLine(parent.Id);



Probably is possible only WSH+WMI solution ,but the main impediment is to find the own process ID.Here are some attemps: http://stackoverflow.com/questions/8296 ... n-vbscript .Will try it later.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Detecting Process ID of the current cmd.exe

#21 Post by foxidrive » 22 Dec 2014 02:09

npocmaka_ wrote:One more way using jscript.net

It works well here in Win 8.1

I've changed the batch code to make it more reliable with spaces in the name etc, and some file checking.

Code: Select all

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal

set "file=%temp%\%~n0-getPID.exe"


   if not exist "%file%" for /f "delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
      if not exist "%file%" "%%v" /nologo /out:"%file%" "%~f0"
   )

if exist "%file%" "%file%"

endlocal & exit /b %errorlevel%

*/


import  System;
import  System.Diagnostics;
import  System.ComponentModel;
import  System.Management;

var myId = Process.GetCurrentProcess().Id;
var query = String.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId);
var search = new ManagementObjectSearcher("root\\CIMV2", query);
var results = search.Get().GetEnumerator();
if (!results.MoveNext()) {
   Console.WriteLine("Error");
   Environment.Exit(-1);
}
var queryObj = results.Current;
var parentId = queryObj["ParentProcessId"];
var parent = Process.GetProcessById(parentId);
Console.WriteLine(parent.Id);

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

Re: Detecting Process ID of the current cmd.exe

#22 Post by Aacini » 22 Dec 2014 05:55

I think this JScript method (WSH+WMI) should work well in all cases (excepting when two instances of the same program run in the same few milliseconds that the program takes to end).

Code: Select all

@if (@CodeSection == @Batch) @then

@echo off
setlocal

for /F %%a in ('csCrIpT //nOlOgO //e:jScRiPt "%~F0"') do set "PID=%%a"
echo %PID%
goto :EOF

@end

var colItems = GetObject("WinMgmts:").ExecQuery("Select CommandLine,ParentProcessID from Win32_Process");
for ( var e = new Enumerator(colItems); ! e.atEnd(); e.moveNext() ) {
   var s = e.item().CommandLine+"";
   if ( s.indexOf("csCrIpT //nOlOgO //e:jScRiPt ") >= 0 ) {
      WScript.Echo(e.item().ParentProcessID);
      WScript.Quit(0);
   }
}

Antonio

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Detecting Process ID of the current cmd.exe

#23 Post by dbenham » 22 Dec 2014 06:56

FINDREPL is "working" for me at work, but not at home. I thought I did the same process at home, but apparantly. I'll check again later.

But even when it "works" - it doesn't :!: :|

I modified Aacini's script to wait until it receives a signal (existence of a file).

Code: Select all

@echo off
setlocal

set "source=wmiCollection('Win32_Process','CommandLine','ParentProcessID')"
set "search=%source:(=\(%"
set "search=%search:)=\)%"

:loop
if not exist go.txt goto :loop

for /F "usebackq tokens=4 delims=," %%a in (`FindRepl "/S:%source%" =search /J`) do set "PID=%%~a" & goto continue
:continue
echo %PID%

I then ran the modified script in 3 different cmd.exe console sessions. They both just sit there, waiting for the GO signal. Finally, in a fourth cmd.exe session, I create the signal using COPY NUL GO.TXT

Obviously I delete GO.TXT and start over when I want to repeat the test.

Aacini's "solution" simply doesn't work. All three sessions reported the same PID, except on some runs, one of the sessions failed entirely with one of two error messages:

D:\test\FindRepl.bat(318, 1) Microsoft JScript runtime error: Permission denied

or

D:\test\FindRepl.bat(322, 1) Microsoft JScript runtime error: Input past end of file


I used the same technique with my code, and it works flawlessly - each session reported its true unique PID:

Code: Select all

@echo off

:getPID  [rtnVar]
setlocal disableDelayedExpansion
set "time="

:loop
if not exist go.txt goto :loop

:getLock
set "lock=%temp%\%~nx0.%time::=.%.lock"
set "uid=%lock:\=:b%"
set "uid=%uid:,=:c%"
set "uid=%uid:_=:u%"
set "uid=%uid:'=:q%"
2>nul ( 9>"%lock%" (
  for /f "skip=1 delims=" %%A in (
    'wmic process where "name='cmd.exe' and CommandLine like '%%<%uid%>%%'" get ParentProcessID'
  ) do for /f "delims=" %%B in ("%%A") do set "PID=%%B"
  (call )
))||goto :getLock
del "%lock%" 2>nul
endlocal & if "%~1" equ "" (echo(%PID%) else set "%~1=%PID%"
exit /b


Siberia-man's PowerShell solution also works, as does npocmaka's/foxidrive's jscript.net solution.

Aacini's JScript solution fails (all 3 sessions report the same PID). This is not surprising given Aacini's statement:
Aacini wrote:I think this JScript method (WSH+WMI) should work well in all cases (excepting when two instances of the same program run in the same few milliseconds that the program takes to end).

One problem is that WMI is relatively slow. The script takes ~0.17 seconds, not a few miliseconds. But even if it were miliseconds, the technique should still be more robust.


Dave Benham

penpen
Expert
Posts: 2009
Joined: 23 Jun 2013 06:15
Location: Germany

Re: Detecting Process ID of the current cmd.exe

#24 Post by penpen » 22 Dec 2014 07:48

dbenham wrote:
penpen wrote:You shouldn't run the WMIC and powershell from within a for/F loop, because then you should get the process id of the for/F cmd instance and not the pid from the batch parent:

We are taking that into account - in fact, it is crucial to how the algorithm works. If you look carefully at my and aGerman's WMIC code, you will see we are returning the ParentProcessID, not the ProcessID.
I saw that, but i assumed, that the WMIC and powershell return their own PID (just as my ProcessInfo.exe does); but it seems it works from the viewpoint of the calling process (unexpected, but onthe other hand... why should someone want to know the PID of the wmic process...).

dbenham wrote:What on earth is ProcessInfo.exe :?:
Dave Benham
Sorry, i forgot to post it - it's just a c# program returning the PID and the parent PID (from the called viewpoint; only tested on winxp home 32 bit); you could compile it using "ProcessInfo.bat":

Code: Select all

// // >nul 2> nul & @goto :main
/*
:main
   @echo off
   setlocal
   cls

   set "csc="

   pushd "%SystemRoot%\Microsoft.NET\Framework"
   for /f "tokens=* delims=" %%i in ('dir /b /o:n "v*"') do (
      dir /a-d /b "%%~fi\csc.exe" >nul 2>&1 && set "csc="%%~fi\csc.exe""
   )
   popd

   if defined csc (
      echo most recent C#.NET compiler located in:
      echo %csc%.
   ) else (
      echo C#.NET compiler not found.
      goto :eof
   )

   for %%a in ("%~dpn0") do for %%b in ("%%~dpna") do (
rem      %csc% /?
rem      %csc% /nologo /optimize /warnaserror /nowin32manifest /unsafe /debug- /target:exe /out:"%%~b.exe" "%~f0"
rem      %csc% /nologo /warnaserror /r:System.dll /r:System.Windows.Forms.dll /r:System.Drawing.dll /target:exe /out:"%~f1.exe" "%~f1.cs"
      %csc% /nologo /r:System.dll /r:System.Management.dll /target:exe /out:"%%~b.exe" "%~f0"
   )
   exit /B
*/

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;


public class ProcessInfo {

   public static void Main (string [] args) {
      int id, parentId;

      if (TryGetProcessIds (out parentId, out id)) {
         Console.WriteLine ("Parent process id: {0}",  parentId);
         Console.WriteLine ("Parent process name: {0}",  Process.GetProcessById (parentId).ProcessName);

         Console.WriteLine ("Actual process id: {0}",  id);
         Console.WriteLine ("Actual process name: {0}",  Process.GetProcessById (id).ProcessName);
         
      } else {
         Console.WriteLine ("Unable to identify caller.");
      }
   }

   static bool TryGetProcessIds (out int parentId, out int id) {
      int ownId = 0;

      try {
         ownId = Process.GetCurrentProcess ().Id;
         ManagementObjectSearcher searcher = new ManagementObjectSearcher ("SELECT * FROM Win32_Process WHERE ProcessId=" + ownId);
         foreach (ManagementBaseObject row in searcher.Get ()) {
            parentId = (int) (uint) row ["ParentProcessId"];
            id = ownId;
            return true;
         }
      } catch {
      }

      parentId = 0;
      id = 0;
      return false;
   }

}

penpen

carlos
Expert
Posts: 503
Joined: 20 Aug 2010 13:57
Location: Chile
Contact:

Re: Detecting Process ID of the current cmd.exe

#25 Post by carlos » 22 Dec 2014 09:19

siberia-man as dbenham says: when cmd is executed it uses the time for set the seed for the random numbers, because it, instead get pid for not use random, you can use random adding entrophy like count the number of cmd instances and also use a for loop for find a free name.

I tested it launching 50 instances of cmd using

Code: Select all

for /l  %a in (1,1,50) do start cmd /c create_tempfile.cmd
(commenting the pause and the del) and it found none duplicate name.

Edit: updated :CountCmd for use find instead findstr and substract 1

Check this:

create_tempfile.cmd

Code: Select all

@Echo Off
SetLocal EnableDelayedExpansion

Call :CreateTempFile
If ErrorLevel 1 (
Echo Can not create a temp file
Exit /B 1
)

Echo Temp File: "!Temp!\!tempfile!"

Pause

Del "!Temp!\!tempfile!"
Goto :Eof

:CreateTempFile
SetLocal EnableDelayedExpansion
Call :CountCmd
Rem advance the pseudo random
For /L %%# In (0,1,%cmd_instances%) Do Echo %Random% > NUL
Rem also use the %cmd_instances% for more entrophy
Set "salt=myscript_%Random%_%cmd_instances%"
Pushd "!Temp!"
Set "tempfile="
For /L %%# in (1,1,2048) Do (
If Not Defined tempfile If Not Exist "!salt!_%%#" (
(TYPE NUL > "!salt!_%%#"
If Not ErrorLevel 1 Set "tempfile=!salt!_%%#"
) >NUL 2>&1
)
)
Popd
(EndLocal & Set "tempfile=%tempfile%")
If Not Defined tempfile Exit /B 1
Exit /B 0

:CountCmd
Set /A "cmd_instances=0"
For /F %%# In (
'"( TASKLIST /NH /FO CSV | FIND /I /C """cmd.exe""" ) 2>NUL"'
) DO Set /A "cmd_instances=%%#-1" 2>NUL
Rem I substract 1 because the cmd.exe used in popen function used by for /f
Exit /B %cmd_instances%


siberia-man
Posts: 208
Joined: 26 Dec 2013 09:28
Contact:

Re: Detecting Process ID of the current cmd.exe

#26 Post by siberia-man » 22 Dec 2014 09:59

carlos wrote:siberia-man as dbenham says

I guess you have addressed your response to another person. What about me, I know this and confirm it (I performed many tests that confirm dbernham's point). :)

npocmaka_
Posts: 516
Joined: 24 Jun 2013 17:10
Location: Bulgaria
Contact:

Re: Detecting Process ID of the current cmd.exe

#27 Post by npocmaka_ » 22 Dec 2014 12:03

penpen wrote:
dbenham wrote:
penpen wrote:You shouldn't run the WMIC and powershell from within a for/F loop, because then you should get the process id of the for/F cmd instance and not the pid from the batch parent:

We are taking that into account - in fact, it is crucial to how the algorithm works. If you look carefully at my and aGerman's WMIC code, you will see we are returning the ParentProcessID, not the ProcessID.
I saw that, but i assumed, that the WMIC and powershell return their own PID (just as my ProcessInfo.exe does); but it seems it works from the viewpoint of the calling process (unexpected, but onthe other hand... why should someone want to know the PID of the wmic process...).

dbenham wrote:What on earth is ProcessInfo.exe :?:
Dave Benham
Sorry, i forgot to post it - it's just a c# program returning the PID and the parent PID (from the called viewpoint; only tested on winxp home 32 bit); you could compile it using "ProcessInfo.bat":

Code: Select all

...

penpen


According to me there's no point to use WMI and C# in this case. C# if far more powerful than jscript (which I prefer only because you can create self-compiled file without toxic output and is a little bit less verbose) and you can use dll import - this should work faster than WMI queries:

http://dotbay.blogspot.com/2009/07/find ... -in-c.html

carlos
Expert
Posts: 503
Joined: 20 Aug 2010 13:57
Location: Chile
Contact:

Re: Detecting Process ID of the current cmd.exe

#28 Post by carlos » 22 Dec 2014 12:48

npocmaka, In my utility sound.exe source code found here I adapted the function for get the pid of parent cmd.

Code: Select all

http://www.consolesoft.com/p/bg/index.html


This is the pure c no c#:

getpid.c

Code: Select all

#include <windows.h>

// compile with tdm-gcc
// gcc -Wl,-e,__start -nostartfiles -O3 -s getpid.c -o getpid.exe -Wall -Wextra

typedef struct tagPROCESSENTRY32 {
    DWORD dwSize;
    DWORD cntUsage;
    DWORD th32ProcessID;
    ULONG_PTR th32DefaultHeapID;
    DWORD th32ModuleID;
    DWORD cntThreads;
    DWORD th32ParentProcessID;
    LONG pcPriClassBase;
    DWORD dwFlags;
    WCHAR szExeFile[MAX_PATH];
} PROCESSENTRY32W, *LPPROCESSENTRY32W;

HANDLE WINAPI CreateToolhelp32Snapshot(DWORD dwFlags, DWORD th32ProcessID);
BOOL WINAPI Process32FirstW(HANDLE hSnapshot, LPPROCESSENTRY32W lppe);
BOOL WINAPI Process32NextW(HANDLE hSnapshot, LPPROCESSENTRY32W lppe);
#define TH32CS_SNAPPROCESS   0x2


DWORD GetIdOfParentProcess(void);
void _start(void);

void _start(void)
{
   ExitProcess(GetIdOfParentProcess());
}

// Return the pid of parent process
// Return 0 if fails getting it
DWORD GetIdOfParentProcess(void)
{
    HANDLE hSnap;
    DWORD currentProcessId;
    PROCESSENTRY32W pe;
    BOOL fOk;

    hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnap == INVALID_HANDLE_VALUE) {
   return 0;
    }

    currentProcessId = GetCurrentProcessId();

    pe.dwSize = sizeof(PROCESSENTRY32W);

    for (fOk = Process32FirstW(hSnap, &pe); fOk;
    fOk = Process32NextW(hSnap, &pe)) {
   if (pe.th32ProcessID == currentProcessId) {
       break;
   }
    }
    CloseHandle(hSnap);
    if (!fOk) {
   return 0;
    }

    return (pe.th32ParentProcessID);
}



You execute it and return in the errorlevel the pid.
This is the executable:

Code: Select all

@Echo Off
Rem Script made using BHX 5.3 { consolesoft.com/p/bhx }
SetLocal EnableExtensions EnableDelayedExpansion
Set "bin=getpid.cab"
Set "size=643"
For %%# In (
"getpid.exe"
"!bin!" "!bin!.da" "!bin!.tmp"
) Do If Exist "%%#" (Del /A /F /Q "%%#" >Nul 2>&1
If ErrorLevel 1 Exit /B 1 )
Findstr /B /N ":+res:!bin!:" "%~f0" >"!bin!.tmp"
(Set /P "inioff=" &Set /P "endoff=") <"!bin!.tmp"
For /F "delims=:" %%# In ("!inioff!") Do Set "inioff=%%#"
For /F "delims=:" %%# In ("!endoff!") Do Set "endoff=%%#"
Set ".=ado=#adodb.stream#"
Set ".=!.!: set a=createobject(ado) : a.type=1 : a.open"
Set ".=!.!: set u=createobject(ado) : u.type=2 : u.open"
Set ".=!.!: set fs=createobject(#scripting.filesystemobject#)"
Set ".=!.!: set s=fs.opentextfile(#%~f0#,1,0,0)"
Set ".=!.!: for i=1 to !inioff! step 1 : s.readline : next"
Set ".=!.!: do while i<!endoff! : d=trim(s.readline)"
Set ".=!.!: for j=1 to len(d) step 2"
Set ".=!.!: u.writetext chrb(#&h#&mid(d,j,2))"
Set ".=!.!: next : i=i+1 : loop"
Set ".=!.!: u.position=2 : u.copyto a : u.close : set u=nothing"
Set ".=!.!: a.savetofile #!bin!#,2 : a.close : set a=nothing"
Set ".=!.!: s.close : set s=nothing : set fs=nothing"
Set ".=!.:#="!"
Echo !.!>"!bin!.da"
Set "ret=1"
Cscript.exe /B /E:vbs "!bin!.da" >Nul
For %%# In ("!bin!") Do If "%%~z#"=="!size!" Set "ret=0"
If "0"=="!ret!" Expand.exe -r "!bin!" -F:* . >Nul
If ErrorLevel 1 Set "ret=1"
Del /A /F "!bin!" "!bin!.da" "!bin!.tmp" >Nul
Exit /B !ret!

:+res:getpid.cab:
4D5343460000000083020000000000002C000000000000000301010001000000
000000004700000001000100000800000000000000009645357D000067657470
69642E65786500DD597C9934020008434BF38D9AC0C0CCC0C0C002C4FFFF3330
EC6080000706C2A00188F9E477F1316CE13CABB883D1E7AC62484666B1424151
7E7A5162AE4272625E5E7E894252AA4251699E42669E828B7FB0426E7E4AAA1E
2F2F970AD48C005706061F466686A7A9334260E63E60E067E66664126760823A
0C0836080009010684EB406C268834234219C4E140F1E21606B0BF181814A0FA
04E0FA05903D61C0C0F08708BF920A5C80E6CAE091D72B49AD2801B9859101EE
173046020A0C01097A45298925890C0C2250AF208709C2CB060E7A9910757FA0
7E02AB63C3507700DD1DA19D4FC3C3821BDFF800D51F7751019B7C9C4505A4FB
C50620D179B8F90D87E181E6DFFF4B225E2C070AF46EDDF3F7FFFFCE1215964E
1995E3AD208E0E5075E7F1171381B240C5AD074A455F5B4015BC68810996A85A
EE3D02545CFA14245C0A14EE6EBD02E437BF61E94DFD121D171F7BB8B7448D01
24190194045A892AD1BB471DEADEE637122F5CFF03DDC0A2F2C21428340119FC
57F530706000D101503A044A4740691728ED03A1FF83523D28ED43E89106DC9D
9DAD14344A5272758D34154CF42CF40C4762288C5CA0618060BF3180945BD840
02503C0F88BB80780610AF03E2030684E582189C73F28B533D12F352725219F6
303817A52696A486E4E7E764A4E614181B05E725161467E4038B427146D78ACC
9280A2FCE4D4E26286FD8CEEA925CEA54545A9793031CF14864E6628DBD8C82D
B3A8B8249CA11B21E2072C51C361653A36ECED1AE4E7EA636CA4979293331AF3
100000
:+res:getpid.cab:

Last edited by carlos on 06 Mar 2015 08:25, edited 1 time in total.

Yury
Posts: 115
Joined: 28 Dec 2013 07:54

Re: Detecting Process ID of the current cmd.exe

#29 Post by Yury » 22 Dec 2014 12:59

dbenham wrote:The cmd.exe process does not have the batch script path in the command line if it was launched from an already running cmd.exe process.


My code is just a special case of the detection process ID.


dbenham wrote:I introduced a pause at the top of the script, and launched two processes via double clicking the script from Windows Explorer. Both sessions returned the same PID.


My code is designed to obtain the PID value only at the time of the starting of the batch file. I'm not going to launch spaceships with this batch file :) .


penpen wrote:You shouldn't run the WMIC and powershell from within a for/F loop, because then you should get the process id of the for/F cmd instance and not the pid from the batch parent


The condition

Code: Select all

CommandLine like '%%%f:\=\\%%%'"
does not include the process with the command line

Code: Select all

cmd /c wmic process where "Name='cmd.exe' and CommandLine like '%%%f:\=\\%%%'" get CreationDate
.


dbenham, what should I do with your code to run it in a batch file that has the name "&ABC.bat"?

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Detecting Process ID of the current cmd.exe

#30 Post by dbenham » 22 Dec 2014 13:11

Yury wrote:dbenham, what should I do with your code to run it in a batch file that has the name "&ABC.bat"?

I put my posted code within a file named "&abc.bat" and it works fine for me. I can run the script using either CALL "&ABC" or CALL ^&ABC.


This thread appears to be a hot topic - lots of interest from many people :!: :shock: 8)


Dave Benham

Post Reply