如何从c#cmdlet修改$env:VARIABLES?
我正在编写一个cmdlet来更改用户临时目录。在此cmdlet中,我还需要更新当前Powershell会话的如何从c#cmdlet修改$env:VARIABLES?,c#,powershell,cmdlet,C#,Powershell,Cmdlet,我正在编写一个cmdlet来更改用户临时目录。在此cmdlet中,我还需要更新当前Powershell会话的$env:TEMP 我尝试这样做的方式是从C#内部运行命令 我是这样做的 首先,我在自定义cmdlet中创建一行命令 string.Format("$env:TEMP = {0}", TempPath).InvokeAsPowershellScript(); 然后我用扩展方法做所有的工作 public static class ExtensionMethods { public
$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 directory变量没有被更改
导入模块“myCustomCommands.dll”
设置临时目录“C:\Foo”
写入主机$env:TEMP#输出'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的重载并使用流程目标。最终返回测试。我同时使用了EnvironmentVariableTarget.Process
和EnvironmentVariableTarget.User
,以便在两个位置更新它。