简体   繁体   中英

c# run powershell command get output as it arrives?

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

The commands are:

Import-Module AppVPkgConverter

Get-Command -Module AppVPkgConverter

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

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

Thanks

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

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM