msbuild, how to set environment variables?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)