gpt4 book ai didi

c# - 如何将此 PowerShell 脚本转换为 C#? - 获取项目属性

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

我可以使用此 PowerShell 命令获取已安装应用程序的列表:

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName

在 C# 中,它不会像我在 PowerShell 中看到的那样返回确切的列表,我需要它来准确显示 PowerShell 的输出。它显示的列表与其他程序完全不同。

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

我做错了什么?谢谢。

最佳答案

If you are talking about content - if you force C# program to run as x64 in Configuration Manager, you'll get the same output. And by default (Any CPU) it was reading from and x86 registry key. Or if you will run Powershell x86, you'll get the same result, as your original C# program


如果您还查询 HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* 键并合并结果,您将获得整个列表。在这种情况下确保您的程序是 x64

PowerShell 的 stdout 中有一些乱七八糟的空格,所以我只是删除了它。

    static void Main(string[] args)
{
var lines = GetSoft("Get-ItemProperty HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*")
.Union(GetSoft("Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*"))
.Distinct()
.ToList();
lines.Sort();

foreach (var line in lines)
{
Console.WriteLine(line);
}
Console.WriteLine(lines.Count);

Console.ReadLine();
}

public static IEnumerable<string> GetSoft(string key)
{
Process p1 = new Process();
ProcessStartInfo psi1 = new ProcessStartInfo("powershell",
key + " | Select-Object DisplayName")
{
RedirectStandardOutput = true,
CreateNoWindow = true
};
p1.StartInfo = psi1;
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.Verb = "runas";
p1.Start();
var output = p1.StandardOutput.ReadToEnd();

var result= output.Split('\r', '\n').Select(s => s.Trim()).Where(s => !String.IsNullOrWhiteSpace(s));

p1.WaitForExit(400);
return result;
}
}

关于c# - 如何将此 PowerShell 脚本转换为 C#? - 获取项目属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36565565/

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