PowerShell script to execute KQL queries against an Azure Log Analytics workspace and export the results to JSON.
- PowerShell 7+
- Azure PowerShell modules:
Install-Module Az.Accounts, Az.OperationalInsights -Scope CurrentUser- Copy
.env.exampleto.envand fill in your values:
WORKSPACE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
TENANT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # optional
SUBSCRIPTION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # optional
- Write your KQL query in a
.kqlfile.
.\Invoke-LogAnalyticsQuery.ps1 -QueryFile .\query.kql -OutputFile .\results.jsonWith a custom config file:
.\Invoke-LogAnalyticsQuery.ps1 -QueryFile .\query.kql -OutputFile .\results.json -ConfigFile .\prod.env| Parameter | Required | Description |
|---|---|---|
-QueryFile |
Yes | Path to the .kql file containing the query |
-OutputFile |
Yes | Path for the JSON output file |
-ConfigFile |
No | Path to the .env config file (default: .env) |
{
"metadata": {
"queryFile": "C:\\path\\to\\query.kql",
"workspaceId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"executedAt": "2026-05-11T10:00:00.000Z",
"rowCount": 200
},
"results": [
{ ... }
]
}- If there is an active Azure session it will be reused; otherwise an interactive login prompt will appear.
- The
.envfile and all*.jsonresult files are excluded from version control via.gitignore.