gpt4 book ai didi

.net - 通过 API 从 C# 附加到 $PSModulePath

转载 作者:行者123 更新时间:2023-12-01 13:40:58 27 4
gpt4 key购买 nike

使用 C#/.Net 执行 PowerShell 脚本时,我想 添加 $PSModulePath 的路径而不覆盖默认的 $PSModulePath。

我已经弄清楚如何使用 InitialSessionState.EnvironmentVariables 将 $PSModulePath 设置为我选择的值。但是,这种方法是不可取 因为它替换了默认的 $PSModulePath 而不是附加到它。

var state= InitialSessionState.CreateDefault();
state.EnvironmentVariables.Add(new SessionStateVariableEntry("PSModulePath", myModuleLoadPath, "PowerShell Module Search Locations"));
var runSpace = RunspaceFactory.CreateRunspace(initialState);

using (var powershell = PowerShell.Create())
{
powershell
.AddScript(script)
.Invoke();
}

有没有办法以编程方式使用 .Net API 附加 到 $PSModulePath?

最佳答案

显然,环境变量PSModulePath未填充默认值 PSModulePath直到Runspace开了。设置 PSModulePath来自 InitialSessionState传递给 RunspaceFactory.CreateRunspace()抑制这种自动填充。

操作默认 PSModulePath , 等到相关Runspace开放中 ,然后根据需要使用 SessionStateProxy.GetVariable() 获取/设置变量/SetVariable() .

using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();

var proxy = runspace.SessionStateProxy;
var psModulePath = proxy.GetVariable("env:PSModulePath");
proxy.SetVariable("env:PSModulePath", $"{psModulePath};{extraPathToAppend}");

using (var powershell = PowerShell.Create())
{
powershell.Runspace = runspace;

powershell
.AddScript(script)
.Invoke();
}
}

访问当前的 PowerShell也可以达到同样的效果实例的 Runspace属性(property)。这种方法消除了显式创建和打开 Runspace 的需要。实例。
using (var powershell = PowerShell.Create())
{
var proxy = powershell.Runspace.SessionStateProxy;
var psModulePath = proxy.GetVariable("env:PSModulePath");
proxy.SetVariable("env:PSModulePath", $"{psModulePath};{extraPathToAppend}");

powershell
.AddScript(script)
.Invoke();

}

感谢提问 Adjust PSModulePath via Runspace in .Net code帮我解决这个问题!

关于.net - 通过 API 从 C# 附加到 $PSModulePath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com