public async Task<Collection<PSObject>> RunPackageCommand(string commandString, bool refreshPackages = true, bool logOutput = true, bool clearBuffer = true)
{
if(logOutput)
isProcessing = true;
if(clearBuffer)
_mainWindowVm.OutputBuffer.Clear();
// Runs the PowerShell runspace in the background.
// Runspace does have a way of running powershell pipelines asynchronously, but making it "async" compatible is a painful and error ridden process.
var result = await Task.Run(() =>
{
lock (_rs)
{
var ps = _rs.CreatePipeline(commandString);
if (logOutput)
{
ps.Output.DataReady += (obj, args) =>
{
var outputs = ps.Output.NonBlockingRead();
foreach (PSObject output in outputs)
{
WriteOutput(output.ToString());
}
};
ps.Error.DataReady += (obj, args) =>
{
var outputs = ps.Error.NonBlockingRead();
foreach (PSObject output in outputs)
{
WriteError(output.ToString());
}
};
}
Collection<PSObject> results = null;
try
{
results = ps.Invoke();
}
catch (Exception e)
{
_mainWindowVm.OutputBuffer.Add(new PowerShellOutputLine {
Text = e.ToString(),
Type = PowerShellLineType.Error
});
return results;
}
_mainWindowVm.OutputBuffer.Add(new PowerShellOutputLine {
Text = "Executed successfully...",
Type = PowerShellLineType.Output
});
if (refreshPackages)
RefreshPackages();
return results;
}
});
if (logOutput)
{
// Gives the user a chance to read the last messages. Should we ditch this?
Thread.Sleep(200);
isProcessing = false;
}
return result;
}