Shaun Luttin
Shaun Luttin

Reputation: 141512

Call MSBuild passing it a single task to run

We can define a target in a csproj file and then specify that target when we call msbuild from the command line. That looks like this:

my.csproj

<Target Name="CopyFiles">
    <Copy
        SourceFiles="@(MySourceFiles)"
        DestinationFolder="c:\MyProject\Destination" />
</Target>

msbuild

msbuild my.csproj /t:CopyFiles

The CopyFiles targets asks msbuild to run the Copy task.

What if we don't want to edit the csproj file. How can we define a target just from the command line? Alternatively, using only the command line, how can we ask msbuild to run just one or maybe two tasks?

Pseudo-Code

msbuild my.csproj /t:"Copy SourceFiles=@(MySourceFiles) DestinationFolder=..."

Upvotes: 1

Views: 812

Answers (1)

makhdumi
makhdumi

Reputation: 1308

Based on the MSBuild Command-Line Reference, this isn't possible exactly as you describe it, i.e. MSBuild will not take Target definitions from the command-line input. They have to be defined in a file somewhere.

But, you can have a script (maybe even a .bat?) that does something like:

  1. Create a new, essentially empty, project file.
  2. Import the .csproj, with <Import Project="foo.csproj" />
  3. Add the targets
  4. Call MSBuild with the new project file with the targets you want. Multiple targets can be specified by multiple /t: switches. Properties can be specified with /p:

The final, programmatically/script generated project file might look something like:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="foo.csproj" />
  <Target Name="CopyFiles">
  <Copy
    SourceFiles="@(MySourceFiles)"
    DestinationFolder="$(Destination)" />
  </Target>
</Project>

The actual MSBuild command called might then be:

msbuild temp.proj /t:CopyFiles /p:"Destination=c:\MyProject\Destination"

Upvotes: 2

Related Questions