Search code examples
msbuildcopymsbuild-taskmsbuild-propertygroup

Msbuild copy to several locations based on list of destination parameter?


I got a directory I want to copy to a number of locations.

Say I have

  • home.aspx

I want to copy it to

  • abc/home.aspx
  • def/home.aspx
  • ghi/home.aspx

so two questions for me:

  • How do I define the list abc, def, ghi?
  • How do I execute my Copy task with each element of this list?

Solution

  • Here is an actual example that I put together that shows what you were looking for:

    <?xml version="1.0" encoding="utf-8"?>
    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Test" ToolsVersion="3.5">
    
      <!--Declare an ItemGroup that points to your file you want to copy.-->
      <ItemGroup>
        <ItemToCopy Include=".\Home.aspx" />
      </ItemGroup>
    
      <!--Declare an ItemGroup that points to your destination Locations-->
      <ItemGroup>
        <DestLocations Include=".\abc\home.aspx" />
        <DestLocations Include=".\def\home.aspx" />
        <DestLocations Include=".\ghi\home.aspx" />
      </ItemGroup>
    
      <Target Name="CopyFiles">
        <!--Run the copy command to copy the item to your dest locations-->
        <!--This is where the magic happens.  The % sign before the DestLocations reference says to use
        Batching.  So Copy will be run for each unique FullPath MetaData in the DestLocations ItemGroup.-->
        <Copy SourceFiles="@(ItemToCopy)" DestinationFolder="%(DestLocations.FullPath)" />
      </Target>
    </Project>