通过 .Net 代码中的 Runspace 调整 PSModulePath [英] Adjust PSModulePath via Runspace in .Net code
问题描述
我正在尝试在运行一些脚本之前设置环境.这个环境由两部分组成.
I'm attempting to setup an environment before running some scripts. This environment is made up of two parts.
- 我想预先加载的几个模块
- 一个充满特定模块的目录,这些模块可以通过简单的导入模块"加载
我可以为正在预加载"的模块指定绝对路径.
I'm ok specifiying the absolute path for the modules that are being 'pre-loaded'.
我正在创建一个 InitialSessionState 对象并调用 ImportPSModule,该方面工作正常.我正在努力的地方是设置模块加载路径.我的目标不是替换那个变量,而是添加它.
I'm creating an InitialSessionState object and calling the ImportPSModule and that aspect is working just fine. Where I'm struggling is getting the module loading path set up. My goal isn't to replace that variable, but to add to it.
我尝试打开运行空间,通过 runspace.SessionStateProxy.GetVariable 和 runspace.SessionStateProxy.SetVariable 调整 env:PSModulePath.问题是这需要我打开运行空间.如果我在完成后尝试关闭它,当我尝试重新打开它时会出现异常.我可以让它保持打开状态,但我不想在代码中的那个时候打开.
I attempted to open the runspace, adjust the env:PSModulePath via the runspace.SessionStateProxy.GetVariable and runspace.SessionStateProxy.SetVariable. The problem is this requires me to open the runspace. If I attempt to close it after I'm done I get exceptions when I try to re-open it. I can leave it open, but I'd prefer not to at that point in my code.
有没有什么方法可以让我在不打开运行空间并在那里设置变量的情况下操纵模块加载路径?
Is there any way for me to manipulate the module loading path without opening up the runspace and setting the variable there?
推荐答案
我只是在我的开发虚拟机上仔细检查了这个,它确实有效.您可以将模块的完整路径指定为 ImportPSModule 的参数,而不是尝试修改 $PSModulePath 变量以指向自定义位置.
I just double checked this on my development vm and it does work. You can specify the full path to the module as a parameter to ImportPSModule instead of trying to modify the $PSModulePath variable to point to a custom location.
static void Main(string[] args)
{
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new[]{@"C:\Users\username\Desktop\Module1\Module1.psd1"});
using(RunspacePool rsp = RunspaceFactory.CreateRunspacePool(iss))
{
rsp.Open();
PowerShell ps = PowerShell.Create();
ps.RunspacePool = rsp;
ps.AddScript("get-command -Module 'Module1'");
foreach(PSObject item in ps.Invoke())
{
Console.WriteLine(item);
}
}
}
这篇关于通过 .Net 代码中的 Runspace 调整 PSModulePath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!