John
John

Reputation: 426

Is there a way to distinguish which batch file ran an executable?

For instance, let's say I have a folder with the following in it:

Each .bat file calls init once or more times. I do not have access to any of the .bat files, so there is not way that I can pass a variable to init.exe. One thing to know about init is a C# application and can accept arguments.

Possibilities:

Am I out of luck? Or is there a hacky method that could work for this?

Upvotes: 1

Views: 250

Answers (3)

John
John

Reputation: 426

The ideas of both Remi and Noodles helped me come to this answer. In C#, I used the following to get the PID of the terminal calling the executable:

//Get PID of current terminal
//Reference: https://github.com/npocmaka/batch.scripts/blob/master/hybrids/.net/getCmdPID.bat

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"];
int myPid = Convert.ToInt32(parentId);

Upvotes: 0

user6017774
user6017774

Reputation:

C:\Windows\system32>wmic process where "commandline like 'notepad'" get parentprocessid
ParentProcessId
5908


C:\Windows\system32>wmic process where "processid=5908" get commandline
CommandLine
C:\Windows\system32\cmd.exe /c ""C:\Users\User\Desktop\New Text Document (2.bat" "

Or to see all info on that batch process

wmic process where "processid=5908" get /format:list

Upvotes: 1

Rémi Boucher
Rémi Boucher

Reputation: 1

This is not the most elegant solution, but if there's only one of those batch file running at a given time, you could try to list all the cmd.exe processes with Process.GetProcessesByName("cmd"), then find the one running one of the batch file by extracting its command line argument using this approach: https://stackoverflow.com/a/2633674/6621790

Upvotes: 0

Related Questions