I need to make a batch file that detects what drive and directory it is in. When I run the the file normally, it is in the correct directory/drive already. But when it is run as admin, it starts in system32. Is there a command that goes to the directory or drive the batch came from?
Asked
Active
Viewed 105 times
2 Answers
4
You could use
Pushd "%~dp0"
This changes the current directory to the path of the batch file.
Quoting the argument makes it safe against special characters in the pathname like "C:\Documents & Settings"

jeb
- 78,592
- 17
- 171
- 225
-
Wish I could upvote twice. Once for the correct answer regarding `%~dp0` and another for suggesting `pushd`. It's a very underused command and I always feel that using `cd` in an automation batch is just wrong :-) – Joey Jun 13 '12 at 06:52
-
Thanks, but at all it's a very simple answer. But you are right, it's an underused command, even in my own scripts I'm using `cd` – jeb Jun 13 '12 at 06:56
-
I try writing batches so that (at least in the successful case) the calling environment doesn't matter and will be restored as if the batch wasn't executes. Which means `setlocal` and `pushd` come in very handy. Might just be a habit of mine, though ;) – Joey Jun 13 '12 at 06:58
-
Thanks a lot, it worked for both directories on c: and other drives. – Genocide Jun 14 '12 at 04:54
0
well a workaround is to use \
before the path to give absolute path.
So, if you need to run a file c:\temp\xyz.exe
and even if you are in directory c:\winodws\system32
still when you do cd \temp\xyz.exe
still the file will run properly

Kshitij
- 8,474
- 2
- 26
- 34