Skip to main content
 首页 » 编程设计

c#之如何修改$env :VARIABLES from c# cmdlets

2024年08月12日36dyllove98

我正在编写一个更改用户 TEMP 目录的 cmdlet。在此 cmdlet 中,我还需要更新当前 Powershell session 的 $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 时,临时目录变量没有改变。

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

请您参考如下方法:

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