3. How do I set environment variables in MSBuild file?

Answered 3. How do I set environment variables in MSBuild file?

All Replies

  • Wednesday, May 26, 2010 1:39 AM
     
     Answered

    There is no direct way to set environment variables by default in an MSBuild file, but you can write a task to do this. The first thing you need is to create a new C# class library project, and write a task like this:

     

    Code Sample:

    using Microsoft.Build.Framework;

    using Microsoft.Build.Utilities;

    namespace MSBuildtasks

    {

        public class SetEnvVar : Task

        {

            private string _variable;

            private string _value;

     

            [Required]

            public string Variable

            {

                get { return _variable; }

                set { _variable = value; }

            }

     

            [Required]

            public string Value

            {

                get { return _value; }

                set { _value = value; }

            }

     

            public override bool Execute()

            {

                Environment.SetEnvironmentVariable(_variable, _value);

                return true;

            }

        }

    }

    And then use it in the project file as follows:

     

    Code Sample:

    <UsingTask TaskName="MSBuildTasks.SetEnvVar"

             AssemblyFile="$(RootDir)Tools\Bin\MSBuildTasks.dll"/>

     

     <PropertyGroup>

      <TestPath>$(VS90COMNTOOLS)..\..</TestPath>

     </PropertyGroup>

     

     <Target Name="PrepareBuildEnvironment">

      <!-- To dump the env run msbuild with /p:DumpEnv=y switch -->

      <SetEnvVar Variable="TestPath" Value="$(TestPath)"/>

      <Message Condition="'$(DumpEnv)' != ''" Text="DumpEnv Requested:" />

      <Exec Condition="'$(DumpEnv)' != ''" Command="set" />

     </Target>

     

    Relative threads:

    http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/0fb8d97d-513e-4d37-8528-52973f65a034

     

    • Marked As Answer by MSDN FAQ Wednesday, May 26, 2010 1:39 AM
    •