Drive letter of given file in windows batch

I'm writing a script where I will get a file name as a parameter. The file will be absolute. (Ideally the solution would support relative files as well, but I can live with absolute-only). It is unknown if the file already exist.

I want to get the Drive letter of the file.

Example:

myScript.bat C:\exampleFolder\somefile.txt D:\someOtherFolder\differentfile.txt

myScript.bat:

echo First argument: %1
echo Second argument: %2
REM Its the next line I have trouble with.
echo Drive letter of second argument: %MAGIC%2

expected output:

First argument: C:\exampleFolder\somefile.txt
Second argument: D:\someOtherFolder\differentfile.txt
Drive letter of second argument: D:

Context: I want to write a script that does some file copy. But the file may appear at the target destination only at once. As soon as its created it must already be complete. So I want to write a script that copies the file to TARGET_DRIVE\tmp and then move it to the destination.

I thought about passing the Drive letter as a third argument. But that seems cumbersome.


I want to get the Drive letter of the file in the 2nd argument

Use %~d2.

myScript.bat:

@echo off
echo First argument: %1
echo Second argument: %2
echo Drive letter of second argument: %~d2

Example Output:

F:\test>myScript C:\exampleFolder\somefile.txt D:\someOtherFolder\differentfile.txt
First argument: C:\exampleFolder\somefile.txt
Second argument: D:\someOtherFolder\differentfile.txt
Drive letter of second argument: D:

F:\test>

Parameter Extensions

When an argument is used to supply a filename then the following extended syntax can be applied:

we are using the variable %1 (but this works for any parameter)

%~f1 Expand %1 to a Fully qualified path name - C:\utils\MyFile.txt

%~d1 Expand %1 to a Drive letter only - C:

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which will be interpreted as an escape character by some commands.

%~n1 Expand %1 to a file Name without file extension C:\utils\MyFile or if only a path is present (with no trailing backslash) - the last folder in that path.

%~x1 Expand %1 to a file eXtension only - .txt

%~s1 Change the meaning of f, n, s and x to reference the Short 8.3 name (if it exists.)

%~1 Expand %1 removing any surrounding quotes (")

%~a1 Display the file attributes of %1

%~t1 Display the date/time of %1

%~z1 Display the file size of %1

%~$PATH:1 Search the PATH environment variable and expand %1 to the fully qualified name of the first match found.

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

%~sp1 Expand %1 to a path shortened to 8.3 characters

%~nx2 Expand %2 to a file name and extension only

Source parameters


Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • parameters - A command line argument (or parameter) is any value passed into a batch script.