![](/img/trans.png)
[英]how to make a C# struct to be compatible with both x86 and x64 without using macro?
[英]How to run PowerShell in x64 or x86 using C#?
我正在使用這個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 OS上運行的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,只要您不選擇“prefer 32-bit”,它就可以與AnyCPU
一起使用
如果您的目的只是獲取顯示名稱,則可能存在“顯示名稱重復”(在兩個注冊表項中)...因此您可以從輸出中刪除它們。 這將刪除重復項並排序:
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();
如果您不想使用進程和捕獲輸出進行修改,可以安裝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());
這應該比調用過程更好:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.