Reputation: 426
For instance, let's say I have a folder with the following in it:
log.bat
clear.bat
new.bat
init.exe
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:
.bat
files.init
that would do something like init %~n0
to get the batch file name. Sadly, this doesn't work either. init.bat
(as the .bat
files call init
, not init.exe
). Then, in the init.bat
file, I would simply put init.exe %~n0
. Two things went wrong with this. First, the .bat
files for some reason took init.exe
priority over init.bat
, and so the batch file alias wasn't even called. Secondly, the %~n0
part expanded to init
, as it was called from init.bat
, not the other batch files.Am I out of luck? Or is there a hacky method that could work for this?
Upvotes: 1
Views: 250
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
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
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