Running Batch Files on Visual Studio 2010 Project Items

Sunday, June 26, 2011 – 10:57 AM

custom_menuThis is something I wrote as an answer on StackOverflow. I dug it out again the other day as I needed it for something else. I have a horrible memory and my blog is essentially just a glorified indexing system for it. Ade’s brain is now, like everything else indexed by Google and Bing and pretty much everyone else.

I’ve updated the steps and, since I completely forgot how to do this, re-tested that they work. So this is slightly more complete that the original SO answer.

Create an external tool menu item that runs batch files

  1. Select Tools –> External Tools…
  2. Add a new tool and set the title to “Run Batch File”
  3. Set the Command to: CMD.EXE
  4. Set the Arguments to: /c “$(ItemPath)”
  5. Set the Initial directory to: $(ItemDir)
  6. Check the “use output window” checkbox and then Apply to create the command
  7. Note where the new command appeared in the list of commands. The external commands are numbered from 1 starting below the divider bar. #1 is usually “Create GUID”

Add a batch file to the solution or project containing the following code:

@echo Running test in:
@cd
@echo Args: %0 %1

Select a batch file in the project and then use the Tools –> Run batch File command you just created to run it. You should see the following output in the VS Output window. Where the paths should refer to the location of your test file.

Running test in:
C:\SrcHg\src
Args: C:\SrcHg\src\test.bat

Add a custom menu item to run the external tool

Now go to Tools -> Customize and select the commands tab.

  1. Select the Context menu radio button and select “Project and Solution Context menus | Item” from the dropdown.
  2. Now use “Add Command…” to add a new command
  3. In the Categories list select “Tools”
  4. From the commands select the “External Command #” that corresponds to the position of the “Run Batch file” custom command you noted the number of in step 7 above.
  5. Move it to the right position in the list add keyboard shortcuts etc.
  6. Close the dialog.

custom_menu_outputNow right click on the batch file and you should see a “Run Batch File” menu item. This will execute the batch file and show it’s output in the VS Output window.

You can add all sorts of commands using this approach. I’ve added custom unit testing commands for WinUnit to the project context menu in my IDE. The only limitation of this approach is that menu items will appear on all item types. There is no way to limit an item to just be associated  .BAT files.

Note: One thing you cannot  easily do is add custom icons. This feature was cut during the re-write of the VS shell to use WPF. A real shame in my opinion. You can read more about this in this blog post on customizing VS.

Sorry, comments for this entry are closed at this time.