6

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

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.