34474Views8Replies

Author Options:

Current drive letter in batch? Answered

I used to have a short code block that would set the drive letter that it's in, to a variable. If I had the batch file on my flash drive (G:), it would set:
G:\
If I had the file on my desktop, it would set:
C:\
Does any one understand what I'm talking about? For the life of me, I can't remember that script...

Discussions

The forums are retiring in 2021 and are now closed for new topics and comments.
0
AndyGadget
AndyGadget

Best Answer 11 years ago

Try :
set drive=%cd:~0,3%
echo %drive%

0
Arbitror
Arbitror

Answer 11 years ago

Thanks! Instead of setting that variable to another variable, I'll just use:
%cd:~0,3%
Instead of %drive%.
0
JeffreyM13
JeffreyM13

5 years ago

To address a path for a file %~dp0Filename.txt such as DEL %~dp0Filename.txt

%~dp0 would give you the
path of the running batch. So, if you run it from inside a folder inside a
folder it would return the DriveLetter\Folder\folder\ but does not Echo.
Outside a batch file.

%CD%
would give you the current path also

Echo%CD%

DriveLetter\Folder\folder

Note
the Missing \ at the end. This is the only thing I have found different about
them.

0
regoldberg
regoldberg

7 years ago

If what you're wanting is to get the letter of the drive on which the batch file resides, for instance to switch back to it after going to %homedrive%, you can go use the %~d0% variable - this will work even when no longer in that drive, so it can be quite handy, even better than %cd:~0,2%

0
FrostSpark
FrostSpark

9 years ago

AndyGadget, thanks a lot it work like a charm :)

0
baudeagle
baudeagle

11 years ago

I believe that you may want to change directroies to access another drive. Isn't the code: CD C: this would change the drive to C: I hope this is what you were asking for.

0
Arbitror
Arbitror

Answer 11 years ago

Read closer:

I used to have a short code block that would set the drive letter that it's in, to a variable.

I mean, if the batch file was on my desktop, which is on my C:\ hard drive, it would set the variable %drive% to the current drive letter, C:\

0
lemonie
lemonie

Answer 11 years ago

Try PM-ing one of the other batch-nuts around here? (I don't know) L