我想编写一个脚本来监视和捕获来自天蓝色网站的错误。为此,我想利用天蓝色的流媒体日志
Powershell脚本。
function Stream-Log
{
Get-AzureWebsiteLog -Name HiWebApiService -Tail
}
Stream-Log
如果我独自执行上述脚本,则会传输日志。
我想从c#客户端调用上面的脚本。
class Program
{
static void Main(string[] args)
{
PowerShell psinstance = PowerShell.Create();
const string getverbose = "$verbosepreference='continue'";
psinstance.AddScript(string.Format(getverbose));
psinstance.Invoke();
psinstance.Commands.Clear();
var scriptPath = @"E:\Azure\LogMonitor\LogMonitor\LogMonitor.ps1";
psinstance.AddScript(scriptPath);
psinstance.Streams.Verbose.DataAdded += Verbose_DataAdded;
psinstance.Streams.Information.DataAdded += Information_DataAdded;
psinstance.Streams.Error.DataAdded += Error_DataAdded;
var results = psinstance.Invoke();
Console.ReadLine();
}
private static void Information_DataAdded(object sender, DataAddedEventArgs e)
{
var newRecord = ((PSDataCollection<InformationRecord>)sender)[e.Index];
Console.WriteLine("information updated: {0}", newRecord.Source);
}
private static void Verbose_DataAdded(object sender, DataAddedEventArgs e)
{
var coll = (PSDataCollection<VerboseRecord>)sender;
var newRecord = (coll)[e.Index];
Console.WriteLine("verbose updated: {0}", newRecord.Message);
}
private static void Error_DataAdded(object sender, DataAddedEventArgs e)
{
ErrorRecord newRecord = ((PSDataCollection<ErrorRecord>)sender)[e.Index];
Console.WriteLine("error updated: {0}", newRecord.ErrorDetails);
}
出于某种原因,上述任何事件都不会捕获蔚蓝流媒体日志的输出。
答案 0 :(得分:0)
根据您的描述,我按照本教程Executing PowerShell scripts from C#来测试此问题。我使用了您的代码并对其进行了修改,然后它可以按预期工作:
class Program
{
static void Main(string[] args)
{
PowerShell psinstance = PowerShell.Create();
psinstance.AddScript("Get-AzureWebsiteLog -Name brucewebapp -Tail");
// prepare a new collection to store output stream objects
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += (s,e)=> {
var newRecord = ((PSDataCollection<PSObject>)s)[e.Index];
Console.WriteLine(newRecord);
};
psinstance.Streams.Verbose.DataAdded += Verbose_DataAdded;
psinstance.Streams.Information.DataAdded += Information_DataAdded;
psinstance.Streams.Error.DataAdded += Error_DataAdded;
psinstance.Invoke(null, outputCollection);
Console.ReadLine();
}
private static void Information_DataAdded(object sender, DataAddedEventArgs e)
{
var newRecord = ((PSDataCollection<InformationRecord>)sender)[e.Index];
Console.WriteLine("information updated: {0}", newRecord.Source);
}
private static void Verbose_DataAdded(object sender, DataAddedEventArgs e)
{
var coll = (PSDataCollection<VerboseRecord>)sender;
var newRecord = (coll)[e.Index];
Console.WriteLine("verbose updated: {0}", newRecord.Message);
}
private static void Error_DataAdded(object sender, DataAddedEventArgs e)
{
ErrorRecord errorRecord = ((PSDataCollection<ErrorRecord>)sender)[e.Index];
Console.WriteLine("error updated: {0}", errorRecord.Exception.Message);
}
}