Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch Script Get Current Drive name

I have a batch file which is on a usb key. I need to know the drive name the batch is in.

Example, if it's E:\mybatch.bat it should find E:\ same thing for F:\, G:\ etc.. when it's opened.

How could I do that in batch script. (Windows)

like image 590
SBSTP Avatar asked Apr 27 '11 23:04

SBSTP


People also ask

What is the current directory in a batch file?

It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2 and you do cd c:\dir3 , then run the batch, the current directory will be c:\dir3 .

What does %% mean in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I change the drive in a batch file?

To change to a specific drive letter while the command prompt directory is using a different drive letter than the one you need to change to, simply use the /D parameter with the CD command (e.g. CD /D <DriveLetter>: ) to change to a different drive letter before running proceeding commands.


2 Answers

%CD% is what you're looking for. It prints the current working directory of the batch file or command running it. If your batch file is on the root of the drive, it will just print the drive letter, otherwise you'll have to parse the first 2 characters.

Example:

echo %CD% 

prints

E:\ 

on a flash drive mounted to E:.

Update: As Andriy said in the comments, if you are just looking for the first three characters of the path, then use this instead of %CD%:

%CD:~0,3% 

This will result in E:\, for example, anywhere on the drive.

like image 108
John Leehey Avatar answered Sep 29 '22 04:09

John Leehey


M$ documentation "Using batch parameters" says:

Modifier: %~d0

Description: Expands %0 to a drive letter.

like image 22
Kai K. Avatar answered Sep 29 '22 04:09

Kai K.