Question: This should be quite simple but I didn`t manage to find it.

If I am running some batch script in cmd, how do I get process id of the hosting cmd?

```
set currentCmdPid= /* some magic */
echo %currentCmdPid%

```

I have found a lot of solutions that use `tasklist` and name filtering but I believe that this won`t work for me, since there can be launched many instances of cmd.

Again, I`d like to have some simple elegant and bullet-proof solution.

Thanks.

Answer: 
Here the topic has been discussed -> <http://www.dostips.com/forum/viewtopic.php?p=38870>

Here's my solution:

```
@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);

```
To get cmd PID, from cmd I run powershell and get parent process Id -- that will be cmd PID. Script gets parent of a parent (since `FOR /F` calls another cmd.exe).

```
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell  -c "(gwmi win32_process | ? processid -eq ((gwmi win32_process | ? processid -eq  $PID).parentprocessid)).parentprocessid"`) DO (
  SET PCT_CleanAfterPID=%%F
)

ECHO %PCT_CleanAfterPID%

```