gpt4 book ai didi

c# - PowerShell - 如何在运行空间中导入模块

转载 作者:可可西里 更新时间:2023-11-01 08:05:35 26 4
gpt4 key购买 nike


我正在尝试在 C# 中创建一个 cmdlet。代码看起来像这样:

[Cmdlet(VerbsCommon.Get, "HeapSummary")]
public class Get_HeapSummary : Cmdlet
{
protected override void ProcessRecord()
{
RunspaceConfiguration config = RunspaceConfiguration.Create();
Runspace myRs = RunspaceFactory.CreateRunspace(config);
myRs.Open();

RunspaceInvoke scriptInvoker = new RunspaceInvoke(myRs);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

Pipeline pipeline = myRs.CreatePipeline();
pipeline.Commands.Add(@"Import-Module G:\PowerShell\PowerDbg.psm1");
//...
pipeline.Invoke();

Collection<PSObject> psObjects = pipeline.Invoke();
foreach (var psObject in psObjects)
{
WriteObject(psObject);
}
}
}

但尝试在 PowerShell 中执行此 CmdLet 时出现此错误:术语 Import-Module 未被识别为 cmdlet 的名称。 PowerShell 中的相同命令不会给我这个错误。如果我改为执行“Get-Command”,我可以看到“Invoke-Module”被列为 CmdLet。

有没有办法在运行空间中执行“导入模块”?

谢谢!

最佳答案

有两种以编程方式导入模块的方法,但我将首先介绍您的方法。您的行 pipeline.Commands.Add("...") 应该只添加命令,而不是命令和参数。参数单独添加:

# argument is a positional parameter
pipeline.Commands.Add("Import-Module");
var command = pipeline.Commands[0];
command.Parameters.Add("Name", @"G:\PowerShell\PowerDbg.psm1")

上面的管道 API 使用起来有点笨拙,尽管它是许多高级 API 的基础,但在许多用途上已被非正式地弃用。在 powershell v2 或更高版本中执行此操作的最佳方法是使用 System.Management.Automation.PowerShell 类型及其流畅的 API:

# if Create() is invoked, a runspace is created for you
var ps = PowerShell.Create(myRS);
ps.Commands.AddCommand("Import-Module").AddArgument(@"g:\...\PowerDbg.psm1")
ps.Invoke()

使用后一种方法的另一种方法是使用 InitialSessionState 预加载模块,这避免了使用 Import-Module 明确为运行空间播种的需要。

InitialSessionState initial = InitialSessionState.CreateDefault();
initialSession.ImportPSModule(new[] { modulePathOrModuleName1, ... });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
RunspaceInvoke invoker = new RunspaceInvoke(runspace);
Collection<PSObject> results = invoker.Invoke("...");

希望这对您有所帮助。

关于c# - PowerShell - 如何在运行空间中导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266108/

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