c# run powershell 命令在到达时获取输出? [英] c# run powershell command get output as it arrives?

查看:84
本文介绍了c# run powershell 命令在到达时获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to run the following Powershell commands from within my c# application and receive the output as they arrive(progress).

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

Ive tried some of the solutions but i either cant seem to get them working or I'm just doing something completely wrong..

命令是:

Import-Module AppVPkgConverter

Get-Command -Module AppVPkgConverter

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

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

Currently I'm just executing a ps1 file which is not ideal as i cant see the output.

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

Any help or a bit of code would be appreciated..

谢谢

推荐答案

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

This is an old question but for the sake of compilation here is my solution:

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

干杯!

这篇关于c# run powershell 命令在到达时获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆