Page 1 of 1

How to fix problems when running scripts as administrator

Posted: 2022-Nov-05, 7:21 am
by Manna5
Yesterday I had a problem with an installer script of BB5 Unlocker. Its job was to create proper directory structure under c:\bb5_unlocker, and copy program files shipped next to the installer into that directory. When I ran that installer as administrator, it has created all the required directories, but failed to copy the files. I did not know why, but after some debugging I found the reason. The file copying commands were:

Code: Select all

copy install.bat c:\bb5_unlocker\
copy bb5_calc.exe c:\bb5_unlocker\
copy bb5logunlocker.exe c:\bb5_unlocker\
copy bb5logunlock.txt c:\bb5_unlocker\
copy bb5_unlocker.cfg c:\bb5_unlocker\logs\
They copied files from the current directory to the installation target directories specified via absolute paths. I wanted to check the current directory of the script, so I inserted this echo command at start of the script:

Code: Select all

echo Current dir: %cd%
pause
And now I discovered the real problem source. Normally the current directory of a script ran from Windows Explorer is the directory where the script is stored, but when you use the "Run as administrator" context menu option, the script current directory is always System32. It seems very important when writing scripts to make them resistant to this problem. Just change the current directory to the real current directory, instead of System32. It is possible to get the real current directory path from the %0 variable, but you first have to strip the script filename. The simplest solution is:

Code: Select all

set realdir=%0
set realdir=%realdir:\script.bat=%
cd %realdir%
Main disadvantage of the above method is the fact that it will not work in case of renaming the script. To make it "rename-proof", you have to use a more complex solution with a loop:

Code: Select all

@echo off
set realdir=\%0
:strip
set stripd=%realdir:~-1%
set realdir=%realdir:~0,-1%
if not %stripd%==\ goto :strip
set realdir=%realdir:~1%
echo Real current directory: %realdir%
cd %realdir%
goto :realdirok

:realdirok
pause

Re: How to fix problems when running scripts as administrator

Posted: 2022-Nov-07, 2:56 am
by Shadow Thief
This is why it's generally recommended to have

Code: Select all

pushd "%~dp0"
at the top of your script.

Re: How to fix problems when running scripts as administrator

Posted: 2022-Nov-08, 9:41 pm
by Simon Sheppard
I have added a note about this to the elevation page, thanks all.