Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter an existing itemgroup so it only includes files that match some condition

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: ''
like image 556
Kaleb Pederson Avatar asked Aug 31 '12 21:08

Kaleb Pederson


2 Answers

<ItemGroup>   <Filtered Include="@(None)" Condition="'%(Extension)' == '.ext'" /> </ItemGroup> 
like image 56
Ilya Kozhevnikov Avatar answered Oct 25 '22 04:10

Ilya Kozhevnikov


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" />
like image 44
LuckyLikey Avatar answered Oct 25 '22 02:10

LuckyLikey