How do you filter an existing ItemGroup based on a specific condition, such as file extension or the item's metadata?
For this example, I'll use the file extension. I'm trying to filter the 'None' ItemGroup defined by VS so that my target can operate on all files of a given extension.
For example, the following may be defined:
<ItemGroup>
<None Include="..\file1.ext" />
<None Include="..\file2.ext" />
<None Include="..\file.ext2" />
<None Include="..\file.ext3" />
<None Include="..\file.ext4" />
</ItemGroup>
I want to filter the 'None' ItemGroup above so it only includes the ext
extension. Note that I do not want to specify all the extensions to exclude, as they'll vary per project and I'm trying to make my target reusable without modification.
I've tried adding a Condition
within a target:
<Target Name="Test">
<ItemGroup>
<Filtered
Include="@(None)"
Condition="'%(Extension)' == 'ext'"
/>
</ItemGroup>
<Message Text="None: '%(None.Identity)'"/>
<Message Text="Filtered: '%(Filtered.Identity)'"/>
</Target>
But sadly, it doesn't work. I get the following for output:
Test:
None: '..\file1.ext'
None: '..\file2.ext'
None: '..\file.ext2'
None: '..\file.ext3'
None: '..\file.ext4'
Filtered: ''
<ItemGroup> <Filtered Include="@(None)" Condition="'%(Extension)' == '.ext'" /> </ItemGroup>
For advanced filtering I suggest using the RegexMatch
from MSBuild Community Tasks.
In this Example we will Filter for Versionnumbers
<RegexMatch Input="@(Items)" Expression="\d+\.\d+\.\d+.\d+">
<Output ItemName ="ItemsContainingVersion" TaskParameter="Output" />
</RegexMatch>
Install MSBuild Community Tasks via Nuget: PM> Install-Package MSBuildTasks or download it here
Then Import it in your MSBuild Script:
<PropertyGroup>
<MSBuildCommunityTasksPath>..\.build\</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import Project="$(MSBuildCommunityTasksPath)MsBuild.Community.Tasks.Targets" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With