如何从c#cmdlet修改$ env:VARIABLES?

时间:2014-11-27 17:31:30

标签: c# powershell cmdlet

我正在编写一个更改用户TEMP目录的cmdlet。在此cmdlet中,我还需要更新当前Powershell会话的$env:TEMP

我尝试这样做的方法是在C#中运行命令。

以下是我的表现方式。

首先,我在自定义cmdlet中创建一行命令

string.Format("$env:TEMP = {0}", TempPath).InvokeAsPowershellScript();

然后我在扩展方法中完成所有工作。

public static class ExtensionMethods
{
    public static void InvokeAsPowershellScript(this string script)
    {
        using (var ps = PowerShell.Create())
        {
            ps.AddScript(script);
            ps.Invoke();
            ps.Commands.Clear();
        }
    }
}

不幸的是,当我运行powershell时,temp目录变量不会被更改。

Import-Module "myCustomCommands.dll"
Set-TempDirectory "C:\Foo"
Write-Host $env:TEMP  # outputs 'C:\TEMP'

如果您有兴趣,请参阅完整的cmdlet

[Cmdlet(VerbsCommon.Set, "TempDirectory"),
Description("Permanently updates the users $env:TEMP directory")]
public class SetTempDirectoryCommand : Cmdlet
{
    private const string _regKey = "HKEY_CURRENT_USER\\Environment";
    private const string _regVal = "TEMP";

    [Parameter(Position = 0, Mandatory = true)]
    public string TempPath { get; set; }

    protected override void ProcessRecord()
    {
        if ((!TempPath.Contains(":\\") && !TempPath.StartsWith("~\\")) || TempPath.Contains("/"))
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("{0} is an invalid path", TempPath);
            Console.ResetColor();
        }
        else
        {
            if (TempPath.StartsWith("~\\"))
            {
                TempPath = TempPath.Replace("~", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
            }

            if (!Directory.Exists(TempPath))
            {
                Directory.CreateDirectory(TempPath);
            }

            Console.WriteLine("Updating your temp directory to '{0}'.", TempPath);
            Registry.SetValue(_regKey,_regVal, TempPath);

            // todo: currently not working
            string.Format("$env:TEMP = {0}", TempPath).InvokeAsPowershellScript();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Successfully updated your TEMP directory to '{0}'", TempPath);
            Console.ResetColor();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

无需修改注册表,您可以使用Environment.SetEnvironmentVariable()方法。使用带有EnvironmentVariableTarget的重载并使用Process目标。