Search code examples
recursionmsbuildcopydirectorybatching

MSbuild batching -- recursive folder copy to multiple destination folders


I am running into a situation. I am trying to use MSBuild batching to copy a folder (subdirectories as well as files) to mutilple dest folders. but when i run the below script, it dumps every content from the src (contents from sub directories too) in root target directory, whereas what i was looking was to get the exact same structure as in src in the target dirs.

<PropertyGroup>
        <Srcfldr>C:\helloworld\REService</Srcfldr>
    <DestFldr>C:\Projects\desire\Examples</DestFldr>
  </PropertyGroup>

  <ItemGroup>
    <SrcToCopy Include="$(Srcfldr)\*.*"/>
  </ItemGroup>

  <ItemGroup>
    <DestToCopy Include="$(DestFldr)/destfldr1"/>
    <DestToCopy Include="$(DestFldr)/destfldr2"/>
    <DestToCopy Include="$(DestFldr)/destfldr3"/>

  </ItemGroup>

   <Target Name="DeployBatching">
    <RemoveDir Directories="@(DestToCopy)"/>
    <MakeDir Directories="@(DestToCopy)"/>

    <Copy SourceFiles="@(SrcToCopy)" DestinationFolder="%(DestToCopy.FullPath)" />

Can you please tell me what am i doing wrong ...

SK


Solution

  • Vanilla copy task is better suited for copying files rather than directories, in any case to preserve structure you need to remap destination using %(RecursiveDir) and %(Filename)%(Extension) metadata. See second example on MSDN.

    Edit:

    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
        <PropertyGroup>
            <Srcfldr>C:\helloworld\REService</Srcfldr>
            <DestFldr>C:\Projects\desire\Examples</DestFldr>
        </PropertyGroup>
    
        <ItemGroup>
            <SrcToCopy Include="$(Srcfldr)\**\*"/>
        </ItemGroup>
    
        <ItemGroup>
            <DestToCopy Include="$(DestFldr)\destfldr1"/>
            <DestToCopy Include="$(DestFldr)\destfldr2"/>
            <DestToCopy Include="$(DestFldr)\destfldr3"/>
        </ItemGroup>
    
        <Target Name="DeployBatching" Outputs="%(DestToCopy.FullPath)">
            <PropertyGroup>
                <DestToCopy>%(DestToCopy.FullPath)</DestToCopy>
            </PropertyGroup>
            <RemoveDir Directories="@(DestToCopy)"/>
            <MakeDir Directories="@(DestToCopy)"/>
            <Copy
                SourceFiles="@(SrcToCopy)"
                DestinationFiles="@(SrcToCopy->'$(DestToCopy)\%(RecursiveDir)\%(Filename)%(Extension)')"
            />
        </Target>
    </Project>