Reputation: 433
I'm able to run a .bat (that runs an .exe that is in the same directory) as administrator: I right-click in the bat file and select "Run as administrator".
To be able to do that, I used the following answer: Run exe from current directory in batch
Here's the code:
@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
start %1myprogram.exe
exit
However, this will only work if the .bat file and the program are in the system drive.
Because if they are, for instance, in a pendrive, and I right-click and select "Run as Administrator", I get the error:
"Windows cannot find 'myprogram.exe'. Make sure you've typed the name correctly, then try again."
Why this happens and how can I fix it? I thought that by using cd %~dp0 it would always point to the folder in which the bat .file resides.
Thanks in advance.
Upvotes: 0
Views: 543
Reputation: 36
Solution
Change cd %~dp0 to cd /d %~dp0
Explanation
When you run something with administrator privileges, the working directory changes to:
'C:\Windows\System32'
Although %~dp0 still points to the drive and the directory containing the batch file, cd %~dp0 does not work, because it only changes the directory, but stays on the same drive.
Using the /d parameter, you can tell the cd-command to change the drive, too.
Upvotes: 1
Reputation: 10819
If the current drive is C: (e.g., the prompt says C:\>
), and you do CD D:\FOO
, the current directory on drive D: is set to \FOO, but you will still be "on" drive C:. Try the following:
@echo off
:A
cls
echo This will start the program.
pause
cd %~dp0
%~d0
start %1myprogram.exe
exit
(also, why %1myprogram.exe
instead of just myprogram.exe
, or even just myprogram
? If you're right-clicking on the batch file to run it, there isn't going to be a %1
.)
Upvotes: 0