Trouble with outputting MSBuild variables

狂风中的少年 提交于 2019-12-06 08:20:23

问题


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.


回答1:


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.




回答2:


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.)



来源:https://stackoverflow.com/questions/2968077/trouble-with-outputting-msbuild-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!