-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInvokeKQL.cs
More file actions
78 lines (69 loc) · 2.91 KB
/
InvokeKQL.cs
File metadata and controls
78 lines (69 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System.Management.Automation;
using System.Linq;
using System.Collections.Generic;
namespace KQL
{
[Cmdlet(VerbsLifecycle.Invoke,"KQL")]
public class InvokeKQL : PSCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public string[] Query { get; set; } = { "StormEvents | count" };
// As per first example at https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/tutorial?pivots=azuredataexplorer
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public string Database { get; set; } = "https://help.kusto.windows.net/Samples";
private Kusto.Data.Common.ICslQueryProvider client;
protected override void BeginProcessing()
{
WriteVerbose($"Connecting database {Database}...");
client = Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider($"{Database};Fed=true;");
}
// This method will be called for each input received from the pipeline to this cmdlet; if no input is received, this method is not called
protected override void ProcessRecord()
{
foreach (string Q1 in Query)
{
WriteVerbose($"Executing query '{Q1}' ...");
try
{
var reader = client.ExecuteQuery(Q1);
WriteVerbose("Parsing query results...");
var fieldNames = Enumerable.Range(0, reader.FieldCount)
.Select(i => reader.GetName(i))
.ToArray();
while (reader.Read())
{
var rowData = new PSObject();
for (int i = 0; i < reader.FieldCount; i++)
{
rowData.Properties.Add(new PSNoteProperty(fieldNames[i], reader.GetValue(i)));
}
WriteObject(rowData);
}
WriteVerbose("Query complete!");
}
catch (Kusto.Data.Exceptions.KustoException ex)
{
WriteError(new ErrorRecord(ex, "KustoQueryError", ErrorCategory.InvalidOperation, Q1));
}
catch (System.Exception ex)
{
WriteError(new ErrorRecord(ex, "QueryExecutionError", ErrorCategory.InvalidOperation, Q1));
}
}
}
// This method will be called once at the end of pipeline execution; if no input is received, this method is not called
protected override void EndProcessing()
{
client.Dispose();
WriteVerbose("End!");
}
}
}