我构建了一个执行 PowerShell 脚本的 32 位 .NET DLL。
我需要它能够以 64 位模式运行脚本and 32-bit.
我已经知道如何使用命令行执行此操作:
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
类,以便异步收集脚本的输出。
@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);
}
}
}
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)