【问题标题】:Executing Powershell script containing Commandlets执行包含命令行开关的 Powershell 脚本
【发布时间】:2018-11-02 17:11:02
【问题描述】:

我需要从 C# 执行包含我的自定义 Commandlets(存在于不同程序集中)的 Powershell 脚本。我尝试了以下方法,但它只调用了一次命令行开关,仅此而已,而在脚本中,命令行开关被多次编写。

Get-MyParameter myTasks

Start-Process notepad.exe

Get-MyParameter myTasks
Get-MyParameter myTasks
Get-MyParameter myTasks

而 MyParameter 是用不同的程序集编写的。 试过的代码是:

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();

我在这里做错了什么?

【问题讨论】:

    标签: c# powershell scripting arguments pipeline


    【解决方案1】:

    您正在将脚本添加到添加了Get-MyParameter 命令的同一管道中。实际上,你正在做

    get-myparameter | { … your script … }
    

    尝试使用单独的管道。

    var result1 = powerShellInstance.AddCommand("Get-MyParameter").Invoke()
    var result2 = powerShellInstance.AddScript(psScript).Invoke();
    

    此外,您可以将模块加载代码简化为

    powerShellInstance.AddCommand("Import-Module").
        AddParameter("Name", @"..\CommandLets\bin\Debug\Commandlets.dll")).
            Invoke();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2021-12-31
      • 1970-01-01
      • 2012-11-06
      相关资源
      最近更新 更多