How to fix problems when running scripts as administrator

Microsoft Windows
Post Reply
User avatar
Manna5
Posts: 14
Joined: 2021-Aug-03, 7:54 am
Contact:

How to fix problems when running scripts as administrator

Post 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
Shadow Thief
Posts: 12
Joined: 2021-Aug-03, 1:45 am

Re: How to fix problems when running scripts as administrator

Post by Shadow Thief »

This is why it's generally recommended to have

Code: Select all

pushd "%~dp0"
at the top of your script.
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: How to fix problems when running scripts as administrator

Post by Simon Sheppard »

I have added a note about this to the elevation page, thanks all.
Post Reply