从C#运行Powershell工作流

时间:2015-05-19 00:00:10

标签: c# powershell workflow powershell-workflow

我试图运行此代码:

    using (PowerShell PowerShellInstance = PowerShell.Create())
    {
        _outputCollection.DataAdded += outputCollection_DataAdded;
        PowerShellInstance.AddScript(@"workflow test { Write-Warning 'this is a warning'; }; test");
        IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, _outputCollection);
    }

但是我收到了这个错误:

  

Windows PowerShell中不支持Windows PowerShell工作流   基于x86的控制台。打开基于Windows PowerShell x64的控制台,然后   然后再试一次。

如何从C#打开基于x64的Powershell实例?

2 个答案:

答案 0 :(得分:2)

这是怎么回事?根据MSDN,“Windows PowerShell 3.0”中引入的PowerShell.Create(RunspaceMode)方法。希望这会有效。

using (PowerShell PowerShellInstance =  PowerShell.Create(RunspaceMode.CurrentRunspace)) {
}

答案 1 :(得分:0)

这是一个解决方法,不涉及尝试使用RunspaceMode.CurrentRunspace(这很难用,因为让dll工作是tricky

WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
//Create and open a runspace.
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    _outputCollection.DataAdded += outputCollection_DataAdded;
     PowerShellInstance.AddScript(@"workflow test { Write-Warning 'this is a warning'; }; test");
     IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, _outputCollection);
}
runspace.Close();