Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run PowerShell as 32-bit or 64-bit from C#

Tags:

c#

powershell

I build a 32-bit .NET DLL that executes PowerShell scripts. I need it to be able to run scripts alternatively as 64-bit and 32-bit.

I already know how to do it with the command line:

C:\Windows\Sysnative\cmd /c powershell -ExecutionPolicy ByPass "& 'script.ps1' arguments"
C:\Windows\SysWOW64\cmd /c powershell -ExecutionPolicy ByPass "& 'script.ps1' arguments"

But I need to be able to use the interface to C#, with either the System.Management.Automation.PowerShell class or the System.Management.Automation.Runspaces.Pipeline class, in order to asynchronously collect outputs from the script.

like image 480
Axel Williot Avatar asked Dec 29 '25 14:12

Axel Williot


1 Answers

The comment from @PetSerAl is the solution. With an out of process runspace, I can change the bitness.

I copy his code here:

using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public static class TestApplication {
    public static void Main() {
        Console.WriteLine(Environment.Is64BitProcess);
        using(PowerShellProcessInstance pspi = new PowerShellProcessInstance()) {
            string psfn = pspi.Process.StartInfo.FileName;
            psfn=psfn.ToLowerInvariant().Replace("\\syswow64\\", "\\sysnative\\");
            pspi.Process.StartInfo.FileName=psfn;
            using(Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi)) {
                r.Open();
                using(PowerShell ps = PowerShell.Create()) {
                    ps.Runspace=r;
                    ps.AddScript("[Environment]::Is64BitProcess");
                    foreach(PSObject pso in ps.Invoke()) {
                        Console.WriteLine(pso);
                    }
                }
            }
        }
    }
}
like image 176
Axel Williot Avatar answered Jan 01 '26 02:01

Axel Williot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!