如何在 C# 中访问 bamboo 变量

How to access bamboo variables in C#

如何在 C# 中访问 bamboo 变量(Plan 和 Branch 变量)?在 powershell 中,我可以使用 $env:bamboo_variableName 访问。我不确定如何在 C# 中执行此操作。这些是我的例子。

Bamboo 变量名称:vCheckoutJob

 var databaseServer = Environment.GetEnvironmentVariable("bamboo_vCheckoutJob"); //returns null
 var databaseServer = Environment.GetEnvironmentVariable("bamboo_vCheckoutJob", EnvironmentVariableTarget.Machine); // returns null

首先,进行一些错误处理可能是个好主意。

让我们检查一下用户是否确实设置了我们正在寻找的特定环境变量:

string bambooEnv;
bool delete_temp_env = false;

bambooEnv = Environment.GetEnvironmentVariable("bamboo_vCheckoutJob");
// Didn't exist, if necessary, create it temporarily.
if (bambooEnv == null) 
{
   Environment.SetEnvironmentVariable("bamboo_vCheckoutJob", "your_value");
   delete_temp_env = true;

   // Now retrieve it.
   bambooEnv = Environment.GetEnvironmentVariable("bamboo_vCheckoutJob");
}

// If we've created it, now delete it.
if (delete_temp_env) { 
   Environment.SetEnvironmentVariable("bamboo_vCheckoutJob", null);

   // Verify Deletion
   if (Environment.GetEnvironmentVariable("bamboo_vCheckoutJob") == null)
      Console.WriteLine("EnvVar var has been deleted again");
}  

包装在函数中:

public static string getEnvironmentVariable(string envVar, string fallbackValue)
{
    bool deleteTempEnv = false;
    string value = Environment.GetEnvironmentVariable(envVar);

    if (value == null)
    {
        Environment.SetEnvironmentVariable(envVar, fallbackValue);
        deleteTempEnv = true;

        value = Environment.GetEnvironmentVariable(envVar);
    }

    if (deleteTempEnv)
    {
        Environment.SetEnvironmentVariable(envVar, null);

        if (Environment.GetEnvironmentVariable(envVar) == null)
        {
            Console.WriteLine("EnvVar has been deleted again");
        }
    }

    return value;
}

用法:

var databaseServer = getEnvironmentVariable("bamboo_vCheckoutJob", "default_path_to_server");

What's happening?

We're checking if the environment variable is set, if it is, return it.

If not

Let's create the environment variable with a default value. If we had to create the environment variable ourselves, lets not keep it in the users system while the program isn't running and delete it again.