Visual Studio 2022 Support
This commit is contained in:
66
CPABuildEventShared/RunPSScript.cs
Normal file
66
CPABuildEventShared/RunPSScript.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using Microsoft.VisualStudio.Shell;
|
||||
using Microsoft.VisualStudio.Shell.Interop;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Management.Automation;
|
||||
using Task = System.Threading.Tasks.Task;
|
||||
|
||||
namespace CPABuildEvents
|
||||
{
|
||||
class RunPSScript
|
||||
{
|
||||
private string _scriptFile;
|
||||
private IVsOutputWindowPane _pane;
|
||||
|
||||
public RunPSScript(string scriptFile, IVsOutputWindowPane pane)
|
||||
{
|
||||
_scriptFile = scriptFile;
|
||||
_pane = pane;
|
||||
}
|
||||
|
||||
public void RunScript()
|
||||
{
|
||||
using (var psi = PowerShell.Create())
|
||||
{
|
||||
psi.AddScript(_scriptFile);
|
||||
psi.Streams.Error.DataAdded += Error_DataAdded;
|
||||
|
||||
var results = psi.Invoke();
|
||||
PrintResults(results);
|
||||
}
|
||||
}
|
||||
|
||||
private void Error_DataAdded(object sender, DataAddedEventArgs e)
|
||||
{
|
||||
var record = ((PSDataCollection<ErrorRecord>)sender)[e.Index];
|
||||
|
||||
PrintRecordAsync(record);
|
||||
}
|
||||
|
||||
private async Task PrintRecordAsync(ErrorRecord record)
|
||||
{
|
||||
if (_pane == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
|
||||
_pane.OutputString($"{Path.GetFileName(_scriptFile)}: {record}\r\n");
|
||||
}
|
||||
|
||||
private void PrintResults(Collection<PSObject> results)
|
||||
{
|
||||
if (_pane == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ThreadHelper.ThrowIfNotOnUIThread();
|
||||
foreach (var result in results)
|
||||
{
|
||||
_pane.OutputString($"{Path.GetFileNameWithoutExtension(_scriptFile)}: {result}\r\n");
|
||||
}
|
||||
_pane.Activate();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user