Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with outputting MSBuild variables

I'm trying to output the variable from one target, into the parent target which started it. For example,

Target 1 simply calls the task in file 2 and is supposed to be able to use the variable set within that. However, I just can't seem to get it to work (wrong syntax perhaps?). Target 1 looks like this:

<Target Name="RetrieveParameter">
    <MSBuild Projects="$(MSBuildProjectFile)" Targets="ObtainOutput" />
    <Message Text="Output = $(OutputVar)" />
</Target>

Target 2 is where it reads in the value of the text file and sets it to the property and sets the variable 'OutputVar' to match. This is supposed to be returned to the parent.

<Target Name="ObtainOutput" Outputs="$(OutputVar)">
    <ReadLinesFromFile File="output.txt">
        <Output TaskParameter="Lines"
                PropertyName="OutputVar" />
    </ReadLinesFromFile>
</Target>

I'm quite new to MSBuild tasks, so it could well be something obvious. All I want to do is set a variable in one task, and then have that available in the parent task which called it.

like image 983
Chris Dobinson Avatar asked Jan 21 '23 23:01

Chris Dobinson


2 Answers

Julien has given you the right answer, but not explained why it is correct.

As you're new to MSBuild tasks, I'll explain why Julien's answer is correct.

All tasks in MSBuild have parameters - you will know them as the attributes that you put on the task. Any of these parameters can be read back out by placing an Output element within it. The Output element has three attributes that can be used:

  • TaskParameter - this is the name of the attribute/parameter on the task that you want to get
  • ItemName - this is the itemgroup to put that parameter value into
  • PropertyName - this is the name of the property to put that parameter value into

In your original scripts, you were invoking one from the other. The second script will execute in a different context, so any property or itemgroup it sets only exists in that context. Therefore when the second script completes, unless you have specified some Output elements to capture values they will be discarded.

Note that you can put more than one Output element under a task to capture multiple parameters or just set the same value to multiple properties/itemgroups.

like image 154
daughey Avatar answered Feb 02 '23 08:02

daughey


You have to use TargetOutputs of the MSBuild task:

 <Target Name="RetrieveParameter">
   <MSBuild Projects="$(MSBuildProjectFile)" Targets="ObtainOutput">
     <Output TaskParameter="TargetOutputs" ItemName="OutputVar"/>
   </MSBuild>
   <Message Text="Output = @(OutputVar)" />
 </Target>

(More information on MSBuild task.)

like image 27
Julien Hoarau Avatar answered Feb 02 '23 08:02

Julien Hoarau