Batch File Dragging


Got another quick tip for ya! Have you ever needed to run the same batch operation on a several files without running it multiple times? I found myself in that situation this week actually. I thought I would share my solution to a common problem. It's easier than you think. You can actually drag and drop a selection of files onto a batch file. Without some code changes this won't run the batch file for each selected file on it's own. But it will pass each selected file name to the batch file as an arguments. Let me illustrate this neat feature.

Say you have a batch file named run.bat. and three data files named: file1.dat file2.dat, and file3.dat. When you click run.bat without dragging, Windows runs the command "run.bat". When you select and drag those three files over run.bat, Windows will pass the file names off as arguments to run.bat. The command ends up being "run.bat file1.dat file2.dat file3.dat". Pretty neat huh? It's a lot faster than typing all that out in shell. But how can we reference those file names in our batch file? Well we can loop or iterate over those arguments and perform the same task on each file.

In the example below, I needed to change the extension on a bunch of files. Sure I could manually rename them or use a wildcard, but what would be the fun in that? So I wrote this batch file to rename each file that gets passed to it as an argument. Now note, when I researched this. I found several different ways to iterate over batch arguments. This one made the most sense to me. If you would like to see some of the others, check out this great Stack Overflow Question for reference. Also feel free to use my example at your own risk. We're not responsible for damages. Till next time, happy batch'n.

:loop
set "file=%1"
move %1 %file:~0,-3%txt
shift
if not "%~1"=="" goto loop
pause
  0

Categories: Quick Tips

Tags: batch