useenvironmentvariablesinabuild

Cancel
Save
Edit

Use Environment Variables in a Build

When you build projects, it is often necessary to set build options using information that is not in the project file or the files that comprise your project. This information is typically stored in environment variables.

In this example, the project file uses environment variables to specify the location of directories.

Environment Variables

All environment variables are available to the MSBuild project file as properties. However, if the project file contains an explicit definition of a property that has the same name as an environment variable, the property in the project file overrides the value of the environment variable. For example, if there is an environment variable named BIN_PATH defined, a project file could use it as follows:

<Project xmlns=”http://schemas.microsoft.com/developer/msbuild/2003”>
<PropertyGroup>
<FinalOutput>$(BIN_PATH)\myassembly.dll</FinalOutput>
</PropertyGroup>
</Project>

You can use a Condition to provide a default value for a property if the environment variable was not set. In the following example, the *ToolsPath* property will have the same value as the TOOLSPATH environment variable if a value was set for the environment variable, but if no value was set, the project file sets the value to c:\tools.

<Project>
<PropertyGroup>
<ToolsPath Condition=”’$(ToolsPath)’ == ‘’”>c:\tools</ToolsPath>
</PropertyGroup>
</Project>

Property names are not case-sensitive so both $('ToolsPath''') and $(TOOLSPATH) reference the same property or environment variable.''

Project Files

Download code

<Project DefaultTargets="FakeBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<PropertyGroup>
<FinalOutput>$(BIN_PATH)\myassembly.dll"</FinalOutput>
<ToolsPath Condition="'$(TOOLSPATH)' == ''">c:\tools</ToolsPath>
</PropertyGroup>

<Target Name="FakeBuild">
<Message Text="Building $(FinalOutput) using the tools at $(ToolsPath)..."/>
</Target>
</Project>