Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I've been working on a batchfile script for a few weeks now that should automate certain routine tasks I need to perform during my work. However, I've stumbled upon a problem which I haven't been able to figure out yet.

I'm using a USB Stick that carries the script and some other software (.exe's). The script requires you to run it in administrator mode so that it can access certain services like Windows Time Service or Windows Update service...

Now I've noticed that when you run the script in administrator mode, It's starting directory is C:\Windows\System32

During this script I wish to run a program that is also on the stick. However it does not find this program. I could write the path to the exact location on the stick. But that will not work because the stick is used on different computers and the drive letter does not always match.

Long story short, I'm looking for a way to run a batch file (that is located on a USB Device) in administrator mode and have that script run a program (Also on the USB Device) automatically.

Thanks in advance! Dempsey

PS: If possible would someone be able to explain how I can make the script log everything to a text file? Keep in mind that the script has a lot of commands in it. It would be nice to have all the output logged into a text file and saved on that same USB Device.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Add these lines to the top of your script:

@setlocal enableextensions
@cd /d "%~dp0"

The first line enables the environmental variables, and the second line is a special variable that refers to the current directory of the script being launched.

Here is a good break down by user wilx in this answer:

cd    -- This is change directory command.
/d    -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0.
%~dp0 -- This can be dissected further into three parts:
%0    -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
%~0   -- The ~ there strips double quotes (") around the expanded argument.
%dp0  -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.
share|improve this answer
    
I have tested this and it has indeed solved my problem. Thank you for your time! –  Dempsey FoxDie Van Assche Jan 4 at 10:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.