c# - Windows PowerShell workflow does not work with Process.Start() or PowerShell.Create()

Viewed 468

I try to run Windows PowerShell workflow script from console application.

Approach 1:

var processInfo = new System.Diagnostics.ProcessStartInfo()
{
            FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
            Arguments = $"\"{scriptFile}\"",
            UseShellExecute = false               
};
System.Diagnostics.Process.Start(processInfo).WaitForExit();

Approach 2 :

 RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
        {
            runspace.Open();
            RunspaceInvoke runspaceInvoke = new RunspaceInvoke(runspace);
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.Add(new Command(scriptFile));
            var psObjects = pipeline.Invoke();
        }

The above two approaches give me the error - Windows PowerShell Workflow is not supported in a Windows PowerShell x86-based console. Open a Windows PowerShell x64-based console, and then try again

Approach 3:

WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ShellUri = "Microsoft.PowerShell.Workflow";
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
PowerShell powershell = PowerShell.Create();
powershell.AddCommand(scriptFile, true);
powershell.Invoke();

Error for Approach 3 - Connecting to remote server localhost failed with the following error message : Access is denied.

I am bit hesitant to use Set-PSSessionConfiguration as I am not much aware of its after effects. I am running this code on Windows Server 2012.

How can I run the workflow using c# ?

1 Answers

As mentioned in the question, I was using Console application to run the Windows PowerShell workflow script.

I changed the app's target platform to 'x64' as the machine has 64-bit OS. It worked.

Earlier the configuration was 'Any CPU'

Any CPU means .NET Framework decides whether to run the program in x64 or x86 bits. But in this case, I was trying to run a PowerShell script which is not a part of console application. Hence I believe I had to specify the target platform as x64.

I was able to run PowerShell Workflow script successfully using C# on Windows Server 2012 R2 & Windows 10 Enterprise. Approach 1 & 2(mentioned in question) both worked.

Related