Retrieve drive letter on Windows

By Eric Downing. Filed in Scripting, Windows  |  
TOP del.icio.us digg

The other day I had to write a script to change to a working directory and back to the original directory. The problem was they were on different drives on Windows. So I had to find a way to capture the drive letter
and switch back to that drive. When using the following command,

cd F:somedir

you are not moved to the “F:” drive without an explicit “F:” command.

The cd Command on windows will show the current directory location. Using some string manipulation on that and capturing it to a variable allows us to go back to that drive.

REM Capture the current drive letter
set ORIGDRIVE=%cd:~0,2%

F:
REM some other scripting things here

REM Return to the original drive letter
ORIGDRIVE

The first line captures the current drive letter by specifying the first character with 0 and the ,2 states to pick up the next 2 characters which would hold the “C:” or whatever drive you started on.

Tags: , , ,

Leave a Reply