Since as long as I can remember, I’ve kept a command-line window open while I worked. It’s a warm fuzzy feeling of how computers used to work. I tend to structure commonly used tasks as msbuild or nant scripts, and then add handy batch files that pass the appropriate parameters to the script.
Unfortunately, most of my team-mates don’t live in the command-line, so running a batch file breaks their traditional flow.
Here’s a short tip on how to execute batch files without having to leave the comfort of the IDE. You’ve probably seen this tip before, but as always, I often use my blog as a digital memory. If it helps you, great.
Visual Studio supports the ability to associate tools and alternate editors for different files. Adding support for batch files is simply a matter of opening the context-menu for a file and choosing “Open With..”. Unfortunately, there’s no mechanism to supply parameters to your program, so adding support for a Command Prompt requires a small subtle hack that passes our parameters to the program we want.
To Associate Batch files to a Custom Command
First, we need to create a simple batch file that passes the arguments that Visual Studio provides onto our batch file.
- If you haven't already, add your batch file to your solution. These are best treated as Solution items that aren’t part of your compilation process.
- Open notepad and save the following script as C:\ExecuteBatch.cmd
@cmd /c %1
Once this is in place,
- Associate the batch file in Visual Studio to the command line by right-clicking on the batch file and choose "Open With...".
- In the dialog that appears, provide a name and associate it to the ExecuteBatch.cmd.
Optional: You can associate the Command as the default program for this extension, by selecting your custom command and clicking on the “Set as Default” button. Note that if you edit the file frequently you might want to skip this step, but you’ll have to right-click the file and choose “Open With…” anytime you want to run your custom command.
Gotchas & Caveats
Just a few closing points:
- If you set your custom command as the default, note that there is no confirmation if you accidentally double-click the batch file. If your script is potentially destructive or long-running, you might want to add a prompt at the beginning of the batch file before running.
- The ExecuteBatch.cmd provided above will close the window immediately after the batch terminates. If you want to review the output of the script before the window closes, you might want to add a pause to the end of the script.
- Lastly, when adding new scripts to Visual Studio it will perform the default action when the file is added to the solution. If you don’t want to run the script when the file is added, you might want to temporarily assign a different editor (Source Code Editor) before you precede.