Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import .targets file from command line in msbuild

I currently have multiple projects being build using msbuild. I have a small customisation to the build that is handled by a .targets file. One solution is to add the snippet

<Import Project="MyTargets.targets"/>

to each project file. However, ideally I would like to not touch the project files, and be able to pass this information as a parameter to msbuild. That way I could easily control whether I run this customisation from the command line, and I don't have to touch the existing project files.

Is this possible?

like image 834
Lawrence Avatar asked Aug 15 '13 08:08

Lawrence


People also ask

How use MSBuild command line?

To run MSBuild at a command prompt, pass a project file to MSBuild.exe, together with the appropriate command-line options. Command-line options let you set properties, execute specific targets, and set other options that control the build process.

How do I get MSBuild command from Visual Studio?

With Visual Studio 2019 and later, it's installed under the Visual Studio installation folder. For a typical default installation on Windows 10, MSBuild.exe is under the installation folder in MSBuild\Current\Bin.

How can we include the response file while executing a command in MSBuild?

This file, MSBuild. rsp, must be in the same directory as MSBuild.exe, otherwise it will not be found. You can edit this file to specify default command-line switches to MSBuild.exe. For example, if you use the same logger every time you build a project, you can add the -logger switch to MSBuild.

What are .targets files?

targets is a user-defined file that provides customizations to projects under a directory. This file is automatically imported from Microsoft. Common. targets unless the property ImportDirectoryBuildTargets is set to false. For more information, Customize your build.


1 Answers

You can do that easily with MSBuild 4.0 (check your version by top-level attribute ToolsVersion="4.0"):

There are multiple properties you can use to import your targets before and after Common.targets and or CSharp.targets loaded.

Simplest way is to use 2 sets of self explaining properties. First set is: $(CustomBeforeMicrosoftCommonTargets) $(CustomAfterMicrosoftCommonTargets)

and second one:

$(CustomBeforeMicrosoftCSharpTargets)
$(CustomAfterMicrosoftCSharpTargets)

Property names are pretty self-explained.

Just pass full file name to any of this properties via msbuild.exe e.g.

msbuild.exe /p:CustomBeforeMicrosoftCSharpTargets=c:\mytargets\custom.targets

You can use other "ImportByWildcard(Before|After)...." properties if you need to import multiple files. But in that case you need to pass more parameters to command-line.

like image 161
Alexey Shcherbak Avatar answered Sep 22 '22 16:09

Alexey Shcherbak