If you are only using the variable in the context of MSBuild...
...then you can use the standard MSBuild variables (aka properties) instead of trying to set an environment variable. You can set properties when running msbuild using the /property
switch (aka /p
switch) (more here), as shown in the example below, which sets the PublishProfile
property to the value Debug
and the VisualStudioVersion
property to the value 15.0
msbuild Project.csproj /p:PublishProfile=Debug /p:VisualStudioVersion=15.0
Find a list of the standard MSBuild's variables/properties at this question
You could also define arbitrary properties in the csproj file itself, using the <PropertyGroup>
element. More on that here
If you do need to set a true environment variable...
...well, it's not an out-of-box thing. You can write a custom task and then leverage it in the project file. Here's a link to an MSDN thread that outlines how to do this:
How to set envrionment variables in MSBuild file? This example creates a new C# class SetEnvVar
which inherits from the Task
class (Microsoft.Build.Utilities.Task
), in the MSBuildTasks
namespace.
//...
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace MSBuildTasks
{
public class SetEnvVar : Task
{
//...
public override bool Execute()
{
Environment.SetEnvironmentVariable(_variable, _value);
return true;
}
... and then the task is invoked by this part of the csproj
file:
<UsingTask
TaskName="MSBuildTasks.SetEnvVar"
AssemblyFile="$(RootDir)Tools\Bin\MSBuildTasks.dll"/>