Reputation: 47
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
Upvotes: 6
Views: 15540
Reputation: 569
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!
Upvotes: 4