Search code examples
msbuildparameter-passingmsbuild-target

MSBuild passing parameters to CallTarget


I'm trying to make a reusable target in my MSBuild file so I can call it multiple times with different parameters.

I've got a skeleton like this:

<Target Name="Deploy">
    <!-- Deploy to a different location depending on parameters -->
</Target>

<Target Name="DoDeployments">
    <CallTarget Targets="Deploy">
        <!-- Somehow indicate I want to deploy to dev -->
    </CallTarget>

    <CallTarget Targets="Deploy">
        <!-- Somehow indicate I want to deploy to testing -->
    </CallTarget>
</Target>

But I can't work out how to allow parameters to be passed into the CallTarget, and then in turn the Target itself.


Solution

  • MSBuild targets aren't designed to receive parameters. Instead, they use the properties you define for them.

    <PropertyGroup>
        <Environment>myValue</Environment>
    </PropertyGroup>
    
    <Target Name="Deploy">
        <!-- Use the Environment property -->
    </Target>
    

    However, a common scenario is to invoke a Target several times with different parameters (i.e. Deploy several websites). In that case, I use the MSBuild MSBuild task and send the parameters as Properties:

    <Target Name="DoDeployments">
        <MSBuild Projects ="$(MSBuildProjectFullPath)"
                 Properties="VDir=MyWebsite;Path=C:\MyWebsite;Environment=$(Environment)"
                 Targets="Deploy" />
    
        <MSBuild Projects ="$(MSBuildProjectFullPath)"
                 Properties="VDir=MyWebsite2;Path=C:\MyWebsite2;Environment=$(Environment)"
                 Targets="Deploy" />
    </Target>
    

    $(MSBuildProjectFullPath) is the fullpath of the current MSBuild script in case you don't want to send "Deploy" to another file.