Today someone was telling me about a co-worker who was having issues with MSBuild. He told me that he was trying to copy a set of files to a set of different servers. But the issue was that he didn’t know how to achieve this without performing multiple Copy task invocations. I told him that he could achieve this using MSBuild Batching. Batching is a process of performing a task (or target) on a set of items (batches) at a time. A batch can also include a single item. So in this scenario we need to perform the copy one time for each server that he wanted to deploy to. I’ve created a simple msbuild file which demonstrates this in two different ways. The first way uses task batching, which can bee seen in the Test target. And the other uses Target batching which can be seen in the DoItCore target. I've also created a clean target, which has nothing to do with batching.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Test">
<ItemGroup>
<SourceFiles Include="*.txt"/>
<Dest Include="One;Two;Three;Four;Five"/>
ItemGroup>
<Target Name="Test">
<Copy SourceFiles ="@(SourceFiles)" DestinationFolder="%(Dest.FullPath)"/>
<Message Text="Fullpath: %(Dest.FullPath)"/>
Target>
<Target Name="DoIt" DependsOnTargets="DoItCore"/>
<Target Name="DoItCore" Inputs="@(SourceFiles)" Outputs="%(Dest.FullPath)">
<Copy SourceFiles="@(SourceFiles)" DestinationFolder="%(Dest.FullPath)"/>
Target>
<Target Name="Clean">
<CreateItem Include="%(Dest.FullPath)\**\*">
<Output ItemName="FilesToDelete" TaskParameter="Include"/>
CreateItem>
<Delete Files="@(FilesToDelete)"/>
Target>
Project>
Batching is an advanced topic of MSBuild, and is defintely neglected. I have to admit I’m guilty of not writing about it enough myself. There are some good batching resources, they are listed below.
How To : Batch Targets with Item Metadata
Batching Brainteaser Explained
Channel 9 : How does MSBuild’s Batching Algorigth Work?
Sayed
Sorry, but I'm just another co-worker gettin brain teased with a realy simple issue... I would like to copy the following directories with files from src\ to dest\ preserving the whole directory structures (results in dest\bin & dest\cfg). I'm interested in doing it "the right way"; maybe just a single invocation?
Any hint would be appreciated!
src
¦
¦ ...
¦
+---cfg
¦ ¦ 01.txt
¦ ¦ 02.txt
¦ ¦ 03.txt
¦ ¦
¦ +---sub
¦ sub_01.txt
¦ sub_02.txt
¦ sub_03.txt
¦ sub_04.txt
¦
+---bin
one.txt
two.txt
three.txt
four.txt
Enjoyed reading about item includes, batches, metadata, property functions... in the 2nd edition of MSBuild and Team Build; just a single errata regarding the Companion Content: the NUnit-ToolPath is an absolute address (see InsideMSBuild\Ch07\nunitExample.proj).
Comments are closed.