Martin
Martin

Reputation: 2086

Define and use a “variable” in a Target

In a Target, I need to use %(Foo.Filename)%(Foo.Extension) several times.

Is there a way to define a “variable” (or something similar) that can be used instead of %(Foo.Filename)%(Foo.Extension)? Preferably inside the Target?

(For the sake of completeness: %(Foo.Identity) is something different.)

Upvotes: 1

Views: 2126

Answers (1)

Ilya Kozhevnikov
Ilya Kozhevnikov

Reputation: 10432

Depends on how the % is being used in that target, as it's not just a shorthand to reference metadata as if it's a class property but a method of batching item groups. Sans some edge cases, e.g. item group of 1, creating a property during execution won't work as it'll overwrite itself on loop; most common way would be to either do target batching, transforms or custom metadata.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Foo Include="*.cs" />
  </ItemGroup>

  <Target Name="Foo">
    <ItemGroup>
      <Foo>
        <Lorem>Ipsum.%(Filename)%(Extension)</Lorem>
      </Foo>
    </ItemGroup>
    <Message Text="%(Foo.Lorem)" />
  </Target>

  <Target Name="Bar">
    <ItemGroup>
      <Lorem Include="Ipsum.%(Foo.Filename)%(Extension)" />
    </ItemGroup>
    <Message Text="@(Lorem)" />
    <Message Text="@(Foo -> 'Ipsum.%(Filename)%(Extension)')" />
  </Target>

  <Target Name="Baz" Inputs="@(Foo)" Outputs="Ipsum.%(Filename)%(Extension)">
    <PropertyGroup>
      <Lorem>Ipsum.%(Foo.Filename)%(Extension)</Lorem>
    </PropertyGroup>
    <Message Text="$(Lorem)" />
  </Target>
</Project>

Upvotes: 3

Related Questions