我正在尝试用 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 会出现以下错误:术语“导入模块”未被识别为 cmdlet 的名称。 PowerShell 中的相同命令不会给我这个错误。如果我执行“Get-Command”,我可以看到“Invoke-Module”被列为 CmdLet。
有没有办法在运行空间中执行“导入模块”?
Thanks!
有两种以编程方式导入模块的方法,但我将首先介绍您的方法。你的线路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("...");
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)