c# - 如何重定向 Powershell 的输出

标签 c# powershell

我有一个类似但不同的问题,例如 How to redirect Powershell output from a script run by TaskScheduler and override default width of 80 characters .

我有一个很久以前写的自定义安装程序框架。在其中我可以执行“任务”。我最近不得不添加一个任务来执行 PowerShell 脚本。现在,即使任务是用 C# 编写的,我也无法直接调用 PowerShell 脚本中的命令。不幸的是,这已经不在讨论范围内了。

简而言之,我想从 C# 调用 PowerShell 可执行文件并将其输出重定向回我的应用程序。这是我到目前为止所做的:

我可以使用以下代码(来 self 创建的测试项目)成功调用 PowerShell:

  string powerShellExeLocation = null;

  RegistryKey localKey = Registry.LocalMachine;

  RegistryKey subKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine");
  powerShellExeLocation = subKey.GetValue("ApplicationBase").ToString();

  if (!Directory.Exists(powerShellExeLocation))
    throw new Exception("Cannot locate the PowerShell dir.");

  powerShellExeLocation = Path.Combine(powerShellExeLocation, "powershell.exe");

  if (!File.Exists(powerShellExeLocation))
    throw new Exception("Cannot locate the PowerShell executable.");

  string scriptLocation = Path.Combine(Environment.CurrentDirectory, "PowerShellScript.ps1");

  if (!File.Exists(scriptLocation))
    throw new Exception("Cannot locate the PowerShell script.");

  ProcessStartInfo processInfo = new ProcessStartInfo();
  processInfo.Verb = "runas";
  processInfo.UseShellExecute = false;
  processInfo.RedirectStandardOutput = true;
  processInfo.RedirectStandardOutput = true;
  processInfo.WorkingDirectory = Environment.CurrentDirectory;

  processInfo.FileName = powerShellExeLocation;
  processInfo.Arguments = "-NoLogo -OutputFormat Text -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + scriptLocation + "\" ";

  Process powerShellProcess = new Process();
  powerShellProcess.StartInfo = processInfo;
  powerShellProcess.OutputDataReceived += new DataReceivedEventHandler(powerShellProcess_OutputDataReceived);
  powerShellProcess.ErrorDataReceived += new DataReceivedEventHandler(powerShellProcess_ErrorDataReceived);

  powerShellProcess.Start();

  while (!powerShellProcess.HasExited)
  {
    Thread.Sleep(500);
  }

我的重定向输出处理程序从未被调用:

void powerShellProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)

void powerShellProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)

我相当有信心脚本正在运行。现在我只有一个输出 PATH 内容的测试脚本。

$a = $env:path; $a.Split(";")

我在 PowerShell 实例中对此进行了测试,它输出正确。

如何使 PowerShell 输出重定向到我的 C# 代码?我不想依赖我将执行的脚本来处理它们自己的日志记录。我宁愿收集他们的输出并在框架的日志记录机制中处理它。

编辑 意识到我在那个代码示例中留下了奇怪的循环等待退出。我有进程“WaitForExit”:

powerShellProcess.WaitForExit();

编辑
使用@MiniBill 的建议。我想出了以下代码片段:

powerShellProcess.Start();
while (!powerShellProcess.HasExited)
{
  string line;
  while (!string.IsNullOrEmpty((line = powerShellProcess.StandardOutput.ReadLine())))
    this.LogInfo("PowerShell running: " + line);
}

这可以很好地处理输出。它把我的台词缩短到 80 个字符 :(,但我可以接受,除非其他人可以提供解决该问题的建议!

更新解决方案

/*
  * The next few lines define the process start info for the PowerShell executable.
  */
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = Environment.CurrentDirectory;

//this FileName was retrieved earlier by looking in the registry for key "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" and the value for "ApplicationBase"
processInfo.FileName = powerShellExeLocation;

//if we're going to use script arguments build up the arguments from the process start correctly.
if (!string.IsNullOrEmpty(this.ScriptArguments))
  processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\" '" + ScriptArguments + "'";
else
  processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\"";

//create the Process object, set the start info, and start the process
Process powerShellProcess = new Process();
powerShellProcess.StartInfo = processInfo;

powerShellProcess.Start();

/*
  * While the PowerShell process hasn't exited do the following:
  * 
  * Read from the current position of the StandardOutput to the end by each line and
  * update the tasks progress with this information
  * 
  * Read from the current position of StandardError to the end by each line, update
  * the task's progress with this information and set that we have an error.
  * 
  * Sleep for 250 milliseconds (1/4 of a sec)
  */
bool isError = false;
while (!powerShellProcess.HasExited)
{
  string standardOuputLine, standardErrorLine;
  while (!string.IsNullOrEmpty((standardOuputLine = powerShellProcess.StandardOutput.ReadLine())))
  {
    this.UpdateTaskProgress(standardOuputLine);
  }


  while (!string.IsNullOrEmpty((standardErrorLine = powerShellProcess.StandardError.ReadLine())))
  {
    this.UpdateTaskProgress(standardErrorLine);
    isError = true;
  }

  Thread.Sleep(250);
}

/*
  * Now that the process has completed read to the end of StandardOutput and StandardError.
  * Update the task progress with this information.
  */

string finalStdOuputLine = powerShellProcess.StandardOutput.ReadToEnd();
string finalStdErrorLine = powerShellProcess.StandardError.ReadToEnd();

if (!string.IsNullOrEmpty(finalStdOuputLine))
  this.UpdateTaskProgress(finalStdOuputLine);

if (!string.IsNullOrEmpty(finalStdErrorLine))
{
  this.UpdateTaskProgress(finalStdErrorLine);
  isError = true;
}

// there was an error during the run of PowerShell that was output to StandardError.  This doesn't necessarily mean that
// the script error'd but there was a problem.  Throw an exception for this.
if (isError)
  throw new Exception(string.Format(CultureInfo.InvariantCulture, "Error during the execution of {0}.", this.ScriptLocation));

最佳答案

您想使用 Process.StandardOutput 属性。这是一个流,您可以打开它来获取程序的输出

关于c# - 如何重定向 Powershell 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11015157/

相关文章:

c# - 使用 "combobox with checkbox"在组合框中显示选中的项目

c# - tcplistener 没有启动

python - Powershell 与 Python 的集成(不是 IronPython)

c# - 如何从 Powershell 调用 GetInstance

javascript - 从 JS 客户端在 SignalR 控制台应用程序上进行身份验证

c# - 使用反射延迟初始化对象

c# - 为什么 AWS Lambda 环境中的 EPPlus Excel 库会抛出 "The type initializer for ' Gdip' 抛出异常”

用于从文件夹列表中省略遍历访问被拒绝的文件夹的 Powershell 脚本

powershell - 如何在 PowerShell 中创建全局常量变量

json - 为 TFS 团队设置区域时参数 'patch' 出现 ArgumentNullException