msbuild, how to set environment variables?

限于喜欢 提交于 2019-12-17 13:44:19

问题


I am trying to set environment variables using project file (ex. .vcxproj)

I looked at property functions but it didn't seem to have such function.

I know there is a way to retrieve environment variable but couldn't find how to set it.

I feel like there should be way to set environment variables in project file.


回答1:


A couple of things:

1) If you are only using the variable in the context of MSBuild, then you can just use the standard MSBuild variables instead of trying to set an environment variable

2) If do need to set an env var, well, it's not an out-of-box thing. You need to write a custom task and then leverage it in the project file. Here's a link to an MSDN thread that outlines how to do this.
http://social.msdn.microsoft.com/forums/en-US/msbuild/thread/0fb8d97d-513e-4d37-8528-52973f65a034




回答2:


The coded task can be put right at the project file since MSBuild v4.0. Like this:

<UsingTask
  TaskName="SetEnvironmentVariableTask"
  TaskFactory="CodeTaskFactory"
  AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v$(MSBuildToolsVersion).dll">

  <ParameterGroup>
    <Name ParameterType="System.String" Required="true" />
    <Value ParameterType="System.String" Required="true" />
  </ParameterGroup>

  <Task>
    <Using Namespace="System" />
    <Code Type="Fragment" Language="cs">
      <![CDATA[
        Environment.SetEnvironmentVariable(Name, Value);
      ]]>
    </Code>
  </Task>

</UsingTask>

Note that in MSBuild 14+, the AssemblyFile reference should be just:

AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll"

The SetEnvironmentVariableTask can be then used from the target:

<Target Name="SampleTarget" BeforeTargets="Build">
  <SetEnvironmentVariableTask Name="TEST_ENV_VAR" Value="$(MSBuildProjectName)" />
</Target>

That's much handier than authoring a separate .DLL for small MSBuild task(s).




回答3:


You might consider writing the environment variables to a text file (.cmd) as a sequence of SET XXX=$(XXX) lines. Then execute the .cmd in the command window.

e.g. Define an ItemGroup with all the SET commands, then use Task 'WriteLinesToFile' to write each item to a line in the .cmd text file.

<ItemGroup>
  <BuildEnvItem Include="REM This file is auto generated. Do not edit" />
  <BuildEnvItem Include="SET TEST_ENV_VAR=$(TEST_ENV_VAR)" />
  <!-- add more as needed -->
<ItemGroup>

<Target Name="DefineBuildEnvironmentVariables">
    <WriteLinesToFile File="Build_env.cmd" Lines="@(BuildEnvItem)" Overwrite="true" Encoding="Unicode"/>
</Target>

This is may be useful in the situation where there is an existing .cmd that is using msbuild. The initial .cmd uses msbuild to generate the Build_env.cmd, and then calls Build_env.cmd before proceeding.



来源:https://stackoverflow.com/questions/14267938/msbuild-how-to-set-environment-variables

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