【问题标题】:Run PowerShell as 32-bit or 64-bit from C#从 C# 以 32 位或 64 位的形式运行 PowerShell
【发布时间】:2019-06-25 05:14:59
【问题描述】:

我构建了一个执行 PowerShell 脚本的 32 位 .NET DLL。 我需要它能够交替运行 64 位 32 位脚本。

我已经知道如何使用命令行:

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

但我需要能够使用 C# 接口,使用 System.Management.Automation.PowerShell 类或 System.Management.Automation.Runspaces.Pipeline 类,以便异步收集脚本的输出。

【问题讨论】:

  • 您需要构建您的 c# 应用程序以专门针对 x86 或 amd64,然后只使用这些类。您无法像在控制台中那样在运行时进行选择。
  • 您明确不能在 32 位应用程序中使用 64 位库。
  • 您可以使用进程外运行空间以与您的进程不同的位数运行 PowerShell。您可以查看示例here

标签: c# powershell


【解决方案1】:

@PetSerAl 的评论是解决方案。使用进程外的运行空间,我可以更改位数。

我在这里复制他的代码:

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

【讨论】:

  • 感谢您的修复.. 它适用于我的项目.. 我从 8 小时开始努力让我的项目工作。我几乎要放弃了,你的代码拯救了我的项目。谢谢
猜你喜欢
  • 2019-12-17
  • 2010-09-16
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 2014-07-23
相关资源
最近更新 更多