c# - 从 C# 运行 build.ps1 时获取 Cake 脚本输出
问题描述
当您使用 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]);
}
}
解决方案
推荐阅读
- python - 创建另一个模型的实例时自动填充 Django 模型字段
- javascript - async.waterfall 最后没有渲染
- mongodb - mongodb 每月交易价值总和
- c++ - 从 FunctionPass 获取 RegionPass 分析信息
- database - 使用 JavaFX 使用 FileChooser 将图像自动上传到文件夹
- azure - 使用 Azure CLI 创建带有 blob 存储触发器的 azure 函数
- google-app-maker - 在 App Maker 中最大化多个用户之间的页面值同步?
- python - keras 重置模型或重置 tensorflow 图
- python - 如何在 Python 中创建评分系统?
- perl - 这是一种有效的插入排序形式吗?