这是为了补充而不是替代@BryanJ的答案。
有两种批处理类型。一种是任务批处理,当您使用%(ItemName.MetaData)
语法时会发生。您只需将此值指定为任务参数,就好像%(ItemName.MetaData)
只会扩展到一个特定值。然后,MSBuild会自动多次执行任务,避免任务明确支持迭代项目列表的需要。
另一种批处理类型是目标批处理。当您使用<Target/>
的Inputs
和Outputs
属性时,目标批处理就会发生。为了在任意项目集上进行批处理,以便目标针对每个项目仅执行一次,您可以指定Inputs="@(ItemName)" Outputs=%(Identity).bogus
。重要的是要存在%(Identity)
。批处理将查看Inputs
和Outputs
的所有可能扩展,并根据这些扩展来决定其批处理。因此,如果您想要为每个项目单独运行目标,则必须确保每个项目都有唯一的扩展。我使用Target批处理样式修改了@BryanJ的代码:
<?xml version="1.0"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="all">
<ItemGroup>
<Messages Include="Message1">
<Text>Hello from Message1</Text>
<Group>1</Group>
</Messages>
<Messages Include="Message2">
<Text>Hello from Message2</Text>
<Group>1</Group>
</Messages>
<Messages Include="Message3">
<Text>Hello from Message3</Text>
<Group>2</Group>
</Messages>
</ItemGroup>
<Target Name="all" DependsOnTargets="TestMessage;TestMessageGrouping" />
<!--
Use the Inputs/Outputs attributes to specify Target
batching. The metadata value I am batching over is
Identity. Since Identity is unique per item, this means the
Target will get run in full once for every value in
Messages. We provide something bogus for Outputs. It is
important that our bogus values do not coincide with real
filenames. If MSBuild finds a file with the name of a value
in Outputs and another file, with an older timestamp,
matching the corresponding value in Inputs, it will skip
running this Target. (This is useful in many situations, but
not when we want to just print out messages!)
-->
<Target Name="TestMessage" Inputs="@(Messages)" Outputs="%(Identity).bogus">
<Message Text="I will print the Text metadata property of %(Messages.Identity)" />
<Message Text="%(Messages.Text)" />
</Target>
<!--
If you want to combine Task and Target batching, you can specify
a different metadata value than Identity to group the items
by. I use the Group metadata I specified in the ItemGroup.
-->
<Target Name="TestMessageGrouping" Inputs="@(Messages)" Outputs="%(Group).bogus">
<Message Text="I will print the Text metadata property of all messages from Group %(Messages.Group)" />
<!--
Now, within the Target batch, we use Task batching to print
all of the messages in our %(Messages.Group) at once.
-->
<Message Text="%(Messages.Text)" />
</Target>
</Project>
输出结果为:
TestMessage:
I will print the Text metadata property of Message1
Hello from Message1
TestMessage:
I will print the Text metadata property of Message2
Hello from Message2
TestMessage:
I will print the Text metadata property of Message3
Hello from Message3
TestMessageGrouping:
I will print the Text metadata property of all messages from Group 1
Hello from Message1
Hello from Message2
TestMessageGrouping:
I will print the Text metadata property of all messages from Group 2
Hello from Message3