如何从 c# cmdlet 修改 $env:变量

本文关键字:env 变量 修改 cmdlet | 更新日期: 2023-09-27 18:32:26

我正在编写一个更改用户 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();
        }
    }
}

不幸的是,当我运行电源外壳时,临时目录变量没有改变。

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();
        }
    }
}

如何从 c# cmdlet 修改 $env:变量

无需修改注册表,可以使用Environment.SetEnvironmentVariable()方法。 使用采用环境变量目标的重载并使用进程目标。