PowerShell-如何在运行空间中导入模块代码如下所示:[Cmdlet(VerbsCommon.Get,"HeapSummary")]publicclassGet_HeapSummary:Cmdlet{运行空间myRs=RunspaceFactory.CreateRunspace(config);myRs.Open();RunspaceInvokescriptInvoker=newRunspaceInvoke(myRs);scriptInvoker.Invoke("Set-ExecutionPolicyUnrestricted");管道pipeline=myRs.CreatePipeline();pipeline.Commands.Add(@"Import-ModuleG:PowerShellPowerDbg.psm1");//...pipeline.Invoke();集合psObjects=pipeline.Invoke();foreach(varpsObjectinpsObjects){WriteObject(psObject);但是尝试在PowerShell中执行此CmdLet给我这个错误:术语Import-Module未被识别为cmdlet的名称。PowerShell中的相同命令不会给我这个错误。如果我执行“Get-Command”,我可以看到列为CmdLet的“Invoke-Module”。有没有办法在Runspace中执行“导入模块”?谢谢!有两种以编程方式导入模块的方法,但我将首先介绍您的方法。您的行pipeline.Commands.Add("...")应该只添加命令,而不是命令和参数。该参数单独添加:#argumentisapositionalparameterpipeline.Commands.Add("Import-Module");varcommand=pipeline.Commands[0];command.Parameters.Add("Name",@"G:PowerShellPowerDbg.psm1")上面的管道API使用起来有点笨拙,并且在许多用途上已被非正式弃用,尽管它是许多更高级API的基础。在powershellv2或更高版本中执行此操作的最佳方法是使用System.Management.Automation.PowerShell类型及其流畅的API:#如果调用Create(),将为您创建一个运行空间varps=PowerShell。创建(我的RS);ps.Commands.AddCommand("Import-Module").AddArgument(@"g:...PowerDbg.psm1")ps.Invoke()使用后一种方法的另一种方法是使用InitialSessionState预加载模块,这样就没有需要使用Import-Module显式地为运行空间播种。有关如何执行此操作的信息,请参阅我的博客:http://nivot.org/nivot2/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule.aspxhttp://nivot.org/blog/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule希望这有帮助。以上就是C#学习教程:PowerShell-HowtoimportmodulesinRunspace的全部内容分享。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。涉及侵权,请点击维权联系管理员删除。如需转载请注明出处:
