Skip to content

Latest commit

 

History

History
65 lines (48 loc) · 2.9 KB

how-to-use-environment-variables-in-a-build.md

File metadata and controls

65 lines (48 loc) · 2.9 KB
title description ms.date ms.topic helpviewer_keywords author ms.author manager ms.subservice
Use Environment Variables in a Build
Work with environment variables in MSBuild project files, and use environment variables to set build options without modifying the project file.
08/15/2023
how-to
environment variables, referencing
projects [.NET Framework], environment variables
MSBuild, environment variables
ghogen
ghogen
mijacobs
msbuild

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.

Reference environment variables

All environment variables that are valid MSBuild property names are available to the Microsoft Build Engine (MSBuild) project file as properties. Valid property names are described in MSBuild properties. For example, environment variables that begin with a number are not available in MSBuild.

Note

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.

To use an environment variable in an MSBuild project

  • Reference the environment variable the same way you would a variable declared in your project file. For example, the following code references the BIN_PATH environment variable:

    <FinalOutput>$(BIN_PATH)\MyAssembly.dll</FinalOutput>

    You can use a Condition attribute to provide a default value for a property if the environment variable was not set.

To provide a default value for a property

  • Use a Condition attribute on a property to set the value only if the property has no value. For example, the following code sets the ToolsPath property to c:\tools only if the ToolsPath environment variable is not set:

    <ToolsPath Condition="'$(TOOLSPATH)' == ''">c:\tools</ToolsPath>

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

Example

The following project file uses environment variables to specify the location of directories.

<Project DefaultTargets="FakeBuild">
    <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>

Related content