gpt4 book ai didi

c# - 如何使用 C# 在 x64 或 x86 中运行 PowerShell?

转载 作者:行者123 更新时间:2023-11-30 12:23:28 25 4
gpt4 key购买 nike

我正在使用此 C# 代码通过 PowerShell 读取我安装的程序。

我需要它通过 PowerShell 读取 x64 和 x86 注册表,我该怎么做?

有重定向的方法吗?或者在 x64 中运行 PowerShell,然后在 x86 中运行?

public void conf() {
process p1 = new Process();
ProcessStartInfo psi1 = new ProcessStartInfo("powershell", "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName");
psi1.RedirectStandardOutput = true;
psi1.CreateNoWindow = true;
p1.StartInfo = psi1;
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.Verb = "runas";
p1.Start();
string output = p1.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p1.WaitForExit(400);
}

最佳答案

如果您的进程在 x64 中运行(或者它是在 x86 操作系统上运行的 x86 进程),则应该这样做。

bool is64 = IntPtr.Size == 8;
var cmdline = "Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* "
+ (is64 ? ",HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*" : "")
+ " | Select-Object DisplayName";
ProcessStartInfo psi1 = new ProcessStartInfo("powershell", cmdline);

如果进程是在 x64 操作系统上运行的 32 位进程,这将不起作用,但对于 .NET,它应该可以与 AnyCPU 一起工作,只要你不选择“prefer 32 位”

更新

如果您的目标只是获取显示名称,则可能存在“显示名称重复项”(在两个注册表项中)...因此您可以将它们从输出中删除。这将删除重复项并排序:

var result = new StringBuilder();
var resultArr = output.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToArray();
Array.Sort(resultArr, StringComparer.InvariantCulture);
foreach (string s in resultArr)
result.AppendLine(s);
output = result.ToString();

更新2

如果您不想处理进程和捕获输出,您可以安装 System.Management.Automation nuget 包并直接使用 powershell。

整个等效程序是:

PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ItemProperty");
var parm = new List<string> {
@"HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
};
if(IntPtr.Size == 8)
parm.Add(@"HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*");
var pso = ps.Invoke(parm);
var result = new StringBuilder();
foreach (var ob in pso)
{
if(ob.Members["DisplayName"] != null)
result.AppendLine(ob.Members["DisplayName"].Value.ToString());
}
Console.WriteLine(result.ToString());

这应该比调用进程更好:-)

关于c# - 如何使用 C# 在 x64 或 x86 中运行 PowerShell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36567426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com