Sergioet
Sergioet

Reputation: 1288

msbuild refer to a env variable

To automate a build, I use a props file with the name of a path env variable that may (or may not) be in the computer. (I hope I'll be able to add a condition later on)

My props file is like this:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <MyVersion>EnvVarPath</MyVersion>
  </PropertyGroup>
</Project>

Then I import that props file in my csproj file and use a copy task to copy a file trying to use $(MyVersion) like this:

  <Target Name="Copy1File" AfterTargets="Build">
    <Message Text="$(MyVersion)" Importance="high" />
    <Copy
      SourceFiles="$(ProjectDir)File.xml"
      DestinationFolder="$(MyVersion)folder\File.xml"
    />

MyVersion var evaluates to "EnvVarPath" string but not the value of the env variable. I also tried using %EnvVarPath% in the props file, but it also evaluates to "%EnvVarPath%", (which can be copied to a file explorer and works), but does not evaluate as the path itself for msbuild.

How could I get that path value in my build?

Upvotes: 0

Views: 1909

Answers (1)

Martin Ullrich
Martin Ullrich

Reputation: 100581

As as been mentioned in the comments, all environment variables are automatically available as Properties - so $(windir) should give the path to the windows directory on windows systems.

Since this may not always be possible to use inline due to added indirection or environment variable names that aren't valid in MSBuild XML (e.g. ProgramFiles(x86)), the necessary static method on System.Environment has been whiteliested in MSBuild and can be used like this:

<PropertyGroup>
  <ProgramFilesVarPrefix>ProgramFiles</ProgramFilesVarPrefix>
  <ProgramFilesVarSuffix>(x86)</ProgramFilesVarSuffix>
  <ProgramFilesLocation>$([System.Environment]::GetEnvironmentVariable('$(ProgramFilesVarPrefix)$(ProgramFilesVarSuffix)'))</ProgramFilesLocation>
</PropertyGroup>

Evaluates to (as displayd in MSBuild Structured Log Viewer): enter image description here

Upvotes: 1

Related Questions