Current drive letter in batch? Answered

31593Views8Replies

Author Options:

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

0
None
AndyGadget

Best Answer 9 years ago

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

0
None
ArbitrorAndyGadget

Answer 9 years ago

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

3 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
None
regoldberg

5 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
None
FrostSpark

7 years ago

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

0
None
baudeagle

9 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
None
Arbitrorbaudeagle

Answer 9 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
None
lemonieArbitror

Answer 9 years ago

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