使用Powershell引导程序(build.ps1)运行Cake脚本时,会获得一些详细的控制台输出,您可以使用-Verbosity选项对其进行进一步配置。
但是,当我从可执行文件(基本上是我们自己的CLI)中运行脚本时,尽管已订阅了所有Powershell数据流,但我并未从cake上获得控制台输出。
有没有办法解决这个问题?
用于执行和获取脚本事件的Powershell代码:
public class PowerShellCommandService: IPowerShellCommandService
{
public void ExecutePowershellScript(string script)
{
Console.WriteLine($@"Executing script: {script}");
using (var localRunspacePool = RunspaceFactory.CreateRunspacePool())
{
localRunspacePool.Open();
using (var engine = System.Management.Automation.PowerShell.Create())
{
engine.RunspacePool = localRunspacePool;
engine.AddScript(script);
engine.Streams.Debug.DataAdded += Debug_DataAdded;
engine.Streams.Information.DataAdded += Information_DataAdded;
engine.Streams.Error.DataAdded += Error_DataAdded;
engine.Streams.Verbose.DataAdded += Verbose_DataAdded;
var asyncResult = engine.BeginInvoke();
Console.WriteLine("Starting script from CLI... ");
var stopwatch = Stopwatch.StartNew();
while (!asyncResult.IsCompleted && stopwatch.ElapsedMilliseconds < 240000)
{
Thread.Sleep(500);
}
stopwatch.Stop();
if (stopwatch.Elapsed.TotalSeconds > 240)
{
Console.WriteLine($"Script timed out after {stopwatch.Elapsed.TotalSeconds}s. Asking Powershell to stop.");
engine.Stop();
Console.WriteLine("Stopped. Script execution aborted..");
//engine.BeginStop((test) => Console.WriteLine("Stopped."), state);
}
else
{
Console.WriteLine($"Script completed in {stopwatch.Elapsed.TotalSeconds}s.");
}
}
}
}
private void Verbose_DataAdded(object sender, DataAddedEventArgs e)
{
if (sender is PSDataCollection<VerboseRecord>)
{
var collection = sender as PSDataCollection<VerboseRecord>;
Console.WriteLine(collection[e.Index]);
}
}
private void Debug_DataAdded(object sender, DataAddedEventArgs e)
{
if (sender is PSDataCollection<DebugRecord>)
{
var collection = sender as PSDataCollection<DebugRecord>;
Console.WriteLine(collection[e.Index]);
}
}
private void Error_DataAdded(object sender, DataAddedEventArgs e)
{
if (sender is PSDataCollection<ErrorRecord>)
{
var collection = sender as PSDataCollection<ErrorRecord>;
Console.WriteLine(collection[e.Index]);
}
}
private void Information_DataAdded(object sender, DataAddedEventArgs e)
{
if (sender is PSDataCollection<InformationRecord>)
{
var collection = sender as PSDataCollection<InformationRecord>;
Console.WriteLine(collection[e.Index]);
}
}