0

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?

Rob
  • 4,327
  • 6
  • 29
  • 55

1 Answers1

2

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>
Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
  • That works really well - thanks! So I can add random "metadata" (if that's the correct term) in an attribute? Never seen that before. – Rob Apr 01 '21 at 16:49
  • Yes you can add metadata and metadata-as-attribute (instead of sub-elements) was added for .NET Core MSbuild projects a few years ago – Martin Ullrich Apr 01 '21 at 17:14