Glenn Lawrence
Glenn Lawrence

Reputation: 3073

How to call .bat file from another .bat file when run as administrator in Windows 7

Here's a simple example with two bat files, caller.bat and callee.bat in the same directory.

caller.bat

call callee.bat
pause

callee.bat

echo "All good"

When I run caller.bat by double clicking it in Explorer it works as expected but if use right-click "Run as administrator" I get

'callee.bat' is not recognized as an internal or external command...

Upvotes: 1

Views: 3272

Answers (2)

Glenn Lawrence
Glenn Lawrence

Reputation: 3073

The problem is that when run as administrator the current working directory is changed to C:\Windows\System32. My solution was to explicitly change the current working directory in caller.bat to be the same as the directory from where the file is run. This is done by extracting the drive and path from the %0 parameter as shown below:

cd /D %~dp0
call callee.bat
pause

The /D argument to cd causes the directory as well as the path to change and is needed to handle the case where the caller .bat file is not on the C: drive.

More info here: Hidden features of Windows batch files

Upvotes: 5

ChrisProsser
ChrisProsser

Reputation: 13108

Another solution is to add the directory where your scripts are stored to your path system environment variable. You could do this through the GUI that windows provides in the advanced system settings (type environment variable into the start menu and you should see the option), or you can run a cmd session as admin and enter: setx path %path%;"your script dir" /M

The /M makes it system wide, not just your user (this is what requires the admin). The double quotes are only required if your path has any spaces in it. The path variable contains a list of paths delimited by semi-colons. The above just appends a new entry to the existing list. Adding an entry to the list allows you to execute programs from this directory without specifying the path.

Finally, if this does not work on it's own you may need to also add .cmd and/or .bat to your pathext variable: setx pathext %pathext%;.cmd;.bat /M

To check the current values of the variables do set var_name i.e.: set pathext

Upvotes: 0

Related Questions