在WPF应用程序中显示Powershell脚本的输出



我有一个WPF应用程序,它执行Powershell脚本,然后在应用程序的文本框中显示一条消息。Powershell脚本的执行方式如下:

string scriptPath = folderPath + "/EXECUTE.ps1";
string powershellPath = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe";
string outputLog = folderPath + "output.log";
bool is64 = IntPtr.Size == 8;
var ENV = "Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* "
+ (is64 ? ",HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" : "")
+ " | Select-Object DisplayName";
ProcessStartInfo startInstall = new ProcessStartInfo(powershellPath, ENV);
startInstall.UseShellExecute = false;
startInstall.Arguments = scriptPath;
startInstall.EnvironmentVariables.Add("RedirectStandardOutput", "true");
startInstall.EnvironmentVariables.Add("RedirectStandardError", "true");
startInstall.EnvironmentVariables.Add("UseShellExecute", "false");
startInstall.EnvironmentVariables.Add("CreateNoWindow", "true");
Process Install = Process.Start(startInstall);
Install.Close();
Console.WriteLine("Script executed successfully");
Console.WriteLine("Output available at: " + outputLog);

Console.WriteLine中的最后两行打印在一个文本框中。我想知道,有没有一种方法可以在这个名为txtboxExecutionResult的文本框中显示Powershell终端窗口的输出?我没有从应用程序中执行任何Powershell命令,只是从应用程序启动并执行EXECUTE.ps1文件。如果能给我指明方向,我将不胜感激。

我曾经在读取另一个应用程序的输出时遇到过类似的问题,我通过读取流程的标准输出解决了这个问题。

Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "example.exe";
process.StartInfo.Arguments = args;
process.Start();
output = await process.StandardOutput.ReadToEndAsync();

最新更新