c# run powershell 命令在到达时获取输出?

Bil*_*Day 6 c# powershell

我希望能够从我的 c# 应用程序中运行以下 Powershell 命令并在它们到达时接收输出(进度)。

我已经尝试了一些解决方案,但我似乎无法让它们工作,或者我只是在做一些完全错误的事情..

命令是:

导入模块 AppVPkgConverter

Get-Command -Module AppVPkgConverter

ConvertFrom-AppvLegacyPackage -DestinationPath "C:\Temp" -SourcePath "C:\Temp2"

目前我只是在执行一个不理想的 ps1 文件,因为我看不到输出。

任何帮助或一些代码将不胜感激..

谢谢

小智 4

这是一个老问题,但为了编译,这里是我的解决方案:

using (PowerShell powerShell = PowerShell.Create()){
  // Source functions.
  powerShell.AddScript("Import-Module AppVPkgConverter");
  powerShell.AddScript("Get-Command -Module AppVPkgConverter");
  powerShell.AddScript("ConvertFrom-AppvLegacyPackage -DestinationPath "C:\Temp" -SourcePath "C:\Temp2"");

  // invoke execution on the pipeline (collecting output)
  Collection<PSObject> PSOutput = powerShell.Invoke();                

  // loop through each output object item
  foreach (PSObject outputItem in PSOutput)
  {
     // if null object was dumped to the pipeline during the script then a null object may be present here
     if (outputItem != null)
     {                      
        Console.WriteLine($"Output line: [{outputItem}]");
     }
   }     

   // check the other output streams (for example, the error stream)
   if (powerShell.Streams.Error.Count > 0)
   {
      // error records were written to the error stream.
      // Do something with the error
   }
}  
Run Code Online (Sandbox Code Playgroud)

干杯!