我构建了一个执行 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"
Run Code Online (Sandbox Code Playgroud)
但是我需要能够使用 C# 的接口,无论是System.Management.Automation.PowerShell类还是System.Management.Automation.Runspaces.Pipeline类,以便异步收集脚本的输出。
@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);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |