You are not logged in.

#1 10 Apr 2016 21:32

Batcher
Member
Registered: 20 Jul 2015
Posts: 56

Get name of file.bat that calls another file

I have 2 files in the same folder the first one's name is unknown and then that file calls 2.bat is there a way that 2.bat can determine the name of the file that called it?

Offline

#2 11 Apr 2016 00:25

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: Get name of file.bat that calls another file

There are several ifs that go along with this.

  • Both scripts have to be running on the same computer (you've already said that they're in the same folder, so you should be fine unless you try to run this on a remote host).

  • Both windows must be open - that is, you have to use start instead of call to open 2.bat.

  • 2.bat must have a custom window title.

  • No other open window can have the same title as 2.bat

@echo off
cls

:: This is the window title of 2.bat
set "second_title=Target script"

for /f "skip=3 tokens=2" %%A in ('tasklist /fi "WINDOWTITLE eq %second_title%"') do set target_pid=%%A
echo PID of 2.bat: %target_pid%

set ppid=
for /f "skip=1" %%A in ('wmic process where "processid=%target_pid%" get parentprocessid') do (
	if not defined ppid set ppid=%%A
)
echo PPID of 2.bat: %ppid%

for /f "tokens=2 delims=:" %%A in ('tasklist /v /fo list /fi "PID eq %ppid%" ^| find "Window Title"') do set "parent_window=%%A"

:: There is a space at the beginning of %parent_window%
echo 2.bat was opened by%parent_window%

:: This is just here so you can read the output; you can remove it if you don't need it.
pause

Offline

#3 11 Apr 2016 00:47

Batcher
Member
Registered: 20 Jul 2015
Posts: 56

Re: Get name of file.bat that calls another file

Thanks Shadow Thief, this is very helpful and thanks for including pause most people dont.

Offline

#4 11 Apr 2016 01:22

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: Get name of file.bat that calls another file

Sure thing; although it's worth noting that if you open a command prompt and run the script from there instead of double-clicking it, you don't even the pause smile

Offline

Board footer

Powered by