Search code examples
c#powershellworkflowpowershell-workflow

Running Powershell Workflow from C#


I'm trying to run this code:

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

But I get this error:

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.

How can I open a x64 based instance of Powershell from C#?


Solution

  • Here is a work around that doesn't involve trying to use RunspaceMode.CurrentRunspace (which is hard to use because getting the dll to work is 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();