msbuildenvironment-variablestargets

Outputting environment variables from MSBuild .targets files


Suppose I had a .targets files which was called as part of a long chain of build related scripts, and used some environment variable. Could you suggest a good way to debug the build process and check the variable's value once the file is reached by the build process?


Solution

  • Environment variables are "read" by MSBuild at the very start of the build process, i.e. when you invoke MSBuild.exe. They are then accessible as properties with the same name as the environment variable (e.g. $(PATH)).

    Thus, it is usually sufficient to list the variables right at startup, if you just need to known the values of the environment variables. In general start MSBuild with the /v:diag. The output will be something like:

    Microsoft (R) Build Engine version 14.0.25420.1 Copyright (C) Microsoft Corporation. All rights reserved.

    C:\Program Files (x86)\MSBuild\14.0\bin\MSBuild.exe /v:diag .\clrinfo32.csproj
    Build started 12.07.2016 14:51:35.
    Environment at start of build:
    ActiveLanguage = en-US
    ALLUSERSPROFILE = C:\ProgramData
    APPDATA = C:\Users\foobar\AppData\Roaming
    ...
    

    Note however, that the value of the environment variable will stay the same for the whole build process (*), the interesting question would be what the value of the MSBuild property (that has been initialized with the value of the environment variable at the start of the build) is at a certain point in time during the build process.

    Property values can be overwritten (by specifying on the command line, by setting the explicitly in <PropertyGroup>-elements, etc.). Also the order of evaluation is significant.

    If you just need to know the value of a property during a task's execution, using <Message Importance="high" Text="$(myproperty)"/> is usually sufficient. Other than that, note that MSBuild execution can also be debugged.

    (*) Assuming no custom task is setting it using something like Environment.SetEnvironmentVariable() behind the scenes. But that in turn doesn't change the value of the property that has been initialized from the variable at the start of MSBuild.