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)
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 .
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.
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.
%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.
M$ documentation "Using batch parameters" says:
Modifier: %~d0
Description: Expands %0 to a drive letter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With