31259Views8Replies

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

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

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

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.

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%

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

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.

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:\

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