If you need to write a DOS batch file that takes a file path as an input parameter and needs to do something to other files in the same directory as the input file then you’ll find there is no easy way to get the file’s directory name into a variable.
You could pass in the directory name as a separate parameter but that seems like cheating. I sometimes find answers to problems like these on Rob van der Woude’s scripting site or Google, but no luck this time.
I had to figure this one out from scratch. Here’s what I do. Let me know if you have a better (shorter) way of doing this.
- Output the result of running ‘dir’ on the file path into a temporary file.
- Loop through the lines in the temporary file, skipping the first three, and then taking the third token.
- Assign that token to a variable.
If all has worked the variable which I’ve called ‘thedirectory’ should now contain the file path.
I’ve tested this on Windows 7 and I’m guessing it will work on other versions of Windows, but I’ll make no promises.
Here is the code:
if not %thedirectory% == "" goto :EOF
dir %1 > %TEMP%\getdir.tmp
for /f "skip=3 tokens=3" %%i in (%temp%\getdir.tmp) do call :setDir %%i
call :getDirectory %1
echo thefile =%1
And if you want to know what I needed it for have a look at my post about stitching together photos using ImageMagick.