Code Scraps: Have MSBuild produce Install and Uninstall batch files for a .NET Windows Service

Here’s a quick code scrap for having MSBuild (or Visual Studio) automatically produce batch files for installing and uninstalling your .NET-based Windows Service. You can also use this same idea to have any other text file produced at compilation time.

<!– Create Install.Bat and Uninstall.Bat files –>
<Target Name=”CreateInstallerFiles” AfterTargets=”AfterCompile”>
“C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe” “$(TargetFileName)”
“C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe” /u “$(TargetFileName)”
<WriteLinesToFile File=”$(OutputPath)install.bat” Overwrite=”true” Lines=”$(InstallerCmd)” />
<WriteLinesToFile File=”$(OutputPath)uninstall.bat” Overwrite=”true” Lines=”$(UninstallerCmd)” />

The above code block can be added to the end of your CSPROJ or VBPROJ file for your project. Note that I’ve specifically set Framework v4 as the installutil version to use – make sure you use the appropriate version for your .NET framework application.

You can have as much text between the two parent properties as you like to create a text file. And you don’t have to be writing batch files – this same logic can be used to write any text format (plain .txt files, javascript, sql statements… whatever plain-text format you need – it’s just a text writer).


<Target Name=”CreateMyTextFiles” AfterTargets=”AfterCompile”>
@echo off
echo This was written to the text file by Visual Studio during the build.
echo Open the OutputPath in Explorer
explorer “$(OutputPath)”
echo Set a variable (only for this script)
SET Random=4
[{“name”:”John Smith”,”age”:30,”occupation”:”Software Tester” },{“name”:”John Doe”,”age”:21,”occupation”:”Some deadbeat loser” }] </SomeJavascriptArray>
FirstName VARCHAR(255),
LastName VARCHAR(255),
EmailAddress VARCHAR(255)
INSERT INTO [USERS] (UserID, FirstName, LastName, EmailAddress) VALUES
<WriteLinesToFile File=”$(OutputPath)mytextfile.cmd” Overwrite=”true” Lines=”$(MyTextFileContent)” />
<WriteLinesToFile File=”$(OutputPath)myjsonarray.json” Overwrite=”true” Lines=”$(SomeJavascriptArray)” />
<WriteLinesToFile File=”$(OutputPath)setup.sql” Overwrite=”true” Lines=”$(DatabaseCreator)” />

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.