[英]Executing Powershell script containing Commandlets
I need to execute Powershell script containing my custom Commandlets ( exist in different assembly) from C#. 我需要从C#执行包含自定义Commandlet(存在于不同程序集中)的Powershell脚本。 I tried following approach but it just invokes the commandlet only once and that's it, while in the script that commandlet is written more than once.
我尝试了以下方法,但是它仅调用一次Commandlet,仅此而已,而在脚本中,多次编写了Commandlet。
Get-MyParameter myTasks
Start-Process notepad.exe
Get-MyParameter myTasks
Get-MyParameter myTasks
Get-MyParameter myTasks
While, MyParameter is written in different assembly. 而MyParameter是用不同的程序集编写的。 Tried Code is :
尝试的代码是:
var powerShellInstance = PowerShell.Create();
powerShellInstance.Runspace = runSpace;
var command = new Command("Import-Module");
command.Parameters.Add("Assembly", Assembly.LoadFrom(@"..\CommandLets\bin\Debug\Commandlets.dll"));
powerShellInstance.Commands.AddCommand(command);
powerShellInstance.Invoke();
powerShellInstance.Commands.Clear();
powerShellInstance.Commands.AddCommand(new Command("Get-MyParameter"));
powerShellInstance.AddScript(psScript);
var result = powerShellInstance.Invoke();
What am I doing wrong here? 我在这里做错了什么?
You are adding the script to the same pipeline you added the Get-MyParameter
command to. 您正在将脚本添加到与添加
Get-MyParameter
命令相同的管道中。 In effect, you are doing 实际上,您在做
get-myparameter | { … your script … }
Try using separate pipelines instead. 请尝试使用单独的管道。
var result1 = powerShellInstance.AddCommand("Get-MyParameter").Invoke()
var result2 = powerShellInstance.AddScript(psScript).Invoke();
Also, you can simplify your module loading code to 另外,您可以简化模块加载代码,以
powerShellInstance.AddCommand("Import-Module").
AddParameter("Name", @"..\CommandLets\bin\Debug\Commandlets.dll")).
Invoke();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.