Repository navigation
Expand file tree
/
Copy pathInvoke-LogAnalyticsQuery.ps1
More file actions
164 lines (127 loc) · 4.68 KB
/
Copy pathInvoke-LogAnalyticsQuery.ps1
File metadata and controls
164 lines (127 loc) · 4.68 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<#
.SYNOPSIS
Executes a KQL query against an Azure Log Analytics workspace and saves the results as JSON.
.PARAMETER QueryFile
Path to the file containing the KQL query.
.PARAMETER OutputFile
Path where the JSON output will be saved.
.PARAMETER ConfigFile
Path to the .env configuration file. Defaults to ".env" in the current directory.
.EXAMPLE
.\Invoke-LogAnalyticsQuery.ps1 -QueryFile .\query.kql -OutputFile .\results.json
.EXAMPLE
.\Invoke-LogAnalyticsQuery.ps1 -QueryFile .\query.kql -OutputFile .\results.json -ConfigFile .\prod.env
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, HelpMessage = 'Path to the KQL query file')]
[ValidateScript({ Test-Path $_ -PathType Leaf })]
[string]$QueryFile,
[Parameter(Mandatory, HelpMessage = 'Path for the JSON output file')]
[string]$OutputFile,
[Parameter(HelpMessage = 'Path to the .env configuration file')]
[string]$ConfigFile = '.env'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
#region --- helpers ---
function Read-EnvFile {
param([string]$Path)
if (-not (Test-Path $Path -PathType Leaf)) {
throw "Config file not found: $Path"
}
$config = @{}
Get-Content $Path | ForEach-Object {
$line = $_.Trim()
if ($line -and $line -notmatch '^\s*#') {
$parts = $line -split '=', 2
if ($parts.Count -eq 2) {
$config[$parts[0].Trim()] = $parts[1].Trim()
}
}
}
return $config
}
function Assert-RequiredModules {
$required = @('Az.Accounts', 'Az.OperationalInsights')
foreach ($module in $required) {
if (-not (Get-Module -ListAvailable -Name $module)) {
throw "Required module '$module' is not installed. Run: Install-Module $module -Scope CurrentUser"
}
}
}
function Connect-AzureInteractive {
param(
[string]$TenantId,
[string]$SubscriptionId
)
$context = Get-AzContext -ErrorAction SilentlyContinue
if (-not $context) {
Write-Host '[AUTH] No active Azure session found. Starting interactive login...' -ForegroundColor Yellow
$connectParams = @{}
if ($TenantId) { $connectParams['TenantId'] = $TenantId }
if ($SubscriptionId) { $connectParams['SubscriptionId'] = $SubscriptionId }
Connect-AzAccount @connectParams | Out-Null
$context = Get-AzContext
}
else {
Write-Host "[AUTH] Reusing existing session: $($context.Account) / $($context.Subscription.Name)" -ForegroundColor Green
}
if ($SubscriptionId -and $context.Subscription.Id -ne $SubscriptionId) {
Write-Host "[AUTH] Switching subscription to $SubscriptionId..." -ForegroundColor Yellow
Set-AzContext -SubscriptionId $SubscriptionId | Out-Null
}
}
#endregion
#region --- main ---
Write-Host ''
Write-Host '=== Log Analytics Query Runner ===' -ForegroundColor Cyan
# 1. Validate required modules
Assert-RequiredModules
# 2. Load configuration
Write-Host "[CONFIG] Loading config from: $ConfigFile"
$config = Read-EnvFile -Path $ConfigFile
$workspaceId = $config['WORKSPACE_ID']
$tenantId = $config['TENANT_ID']
$subscriptionId = $config['SUBSCRIPTION_ID']
if ([string]::IsNullOrWhiteSpace($workspaceId)) {
throw "WORKSPACE_ID is not defined in $ConfigFile"
}
# 3. Connect to Azure
Connect-AzureInteractive -TenantId $tenantId -SubscriptionId $subscriptionId
# 4. Read KQL query
Write-Host "[QUERY] Reading KQL from: $QueryFile"
$kqlQuery = Get-Content -Path $QueryFile -Raw
if ([string]::IsNullOrWhiteSpace($kqlQuery)) {
throw "The query file is empty: $QueryFile"
}
Write-Host "[QUERY] Executing query against workspace: $workspaceId"
# 5. Execute query
$queryResult = Invoke-AzOperationalInsightsQuery `
-WorkspaceId $workspaceId `
-Query $kqlQuery
if ($null -eq $queryResult) {
throw 'The query returned no response from the API.'
}
# 6. Extract rows — Results is a IEnumerable; materialize it
$rows = @($queryResult.Results)
Write-Host "[RESULT] $($rows.Count) row(s) returned."
# 7. Build output object with metadata
$output = [ordered]@{
metadata = [ordered]@{
queryFile = (Resolve-Path $QueryFile).Path
workspaceId = $workspaceId
executedAt = (Get-Date -Format 'o') # ISO 8601
rowCount = $rows.Count
}
results = $rows
}
# 8. Save JSON
$outputDir = Split-Path $OutputFile -Parent
if ($outputDir -and -not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
}
$output | ConvertTo-Json -Depth 20 | Set-Content -Path $OutputFile -Encoding UTF8
Write-Host "[OUTPUT] Results saved to: $((Resolve-Path $OutputFile).Path)" -ForegroundColor Green
Write-Host ''
#endregion