运行 来自 C# 的 Powershell 工作流

Running Powershell Workflow from C#

我正在尝试 运行 此代码:

    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 Workflow is not supported in a Windows PowerShe ll x86-based console. Open a Windows PowerShell x64-based console, and then try again.

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

这个怎么样?根据 MSDN,PowerShell.Create(RunspaceMode) 方法在 'Windows PowerShell 3.0' 中引入。希望这会奏效。

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

这是一个不涉及尝试使用 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();