msbuilditemgroup

Msbuild: Filter itemgroup based on file contents


I need to filter an ItemGroup (containing filenames) based on the contents of the file. But I cannot get this to work.

  <ItemGroup>
      <FilteredFiles Include="@(AllFiles)" 
      Condition="$([System.IO.File]::ReadAllText(%(Identity)).Contains('searchText'))" />
  </ItemGroup>

I get this error:

error MSB4184: The expression "[System.IO.File]::ReadAl lText(%(Identity))" cannot be evaluated. Could not find file 'C:\builds\git\RadarTemp%(Identity)'

Any suggestions?


Solution

  • I belive the most compatible way would be to use an intermediate item:

    <ItemGroup>
      <AllFilesWithSearchResult Include="@(AllFiles)" 
        ContainsSearchText="$([System.IO.File]::ReadAllText('%(Identity)').Contains('searchText'))" />
      <FilteredFiles Include="@(AllFilesWithSearchResult->WithMetadataValue('ContainsSearchText','True'))"/>
    </ItemGroup>