从c#运行Powershell工作流

本文关键字:工作流 Powershell 运行 | 更新日期: 2023-09-27 17:49:35

我想运行这段代码:

    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实例?

从c#运行Powershell工作流

这个怎么样?根据MSDN, PowerShell. create (RunspaceMode)方法是在"Windows PowerShell 3.0"中引入的。希望这能奏效。

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

这是一个不涉及尝试使用RunspaceMode.CurrentRunspace的工作(这很难使用,因为让dll工作是棘手的)

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