# Query Azure Log Analytics with PowerShell and Export Results Correctly

Author: [Opeyemi Enitan](https://blog.threatintels.org/blog/about.html)

Canonical article: https://blog.threatintels.org/blog/log-analytics-powershell-workspace-id.html

Historical project period: July 2025 (2025-07)

## Why this matters

Automated security reports and evidence exports can fail when an Azure Log Analytics query is sent to the wrong workspace or the wrong workspace identifier is supplied. Confusing log queries with management-plane inventory can also produce an incomplete or misleading report.

This guide explains how to resolve the correct workspace, query it with PowerShell and validate CSV or JSON outputs so that reporting and investigation workflows have reliable data.

PRACTICAL WALKTHROUGH

## What you'll accomplish

Fix common Invoke-AzOperationalInsightsQuery parameter errors, retrieve data and export reliable CSV and JSON output.

### Before you begin

- Az.OperationalInsights PowerShell module and authorised Azure sign-in
- Read access to the selected subscription, resource group and workspace
- A known test query and a suitable time range

**Verify the result:** Confirm the workspace CustomerId is used for querying, test results in the selected workspace and verify exported records and management-plane table inventory separately.

## Understand workspace-name and query-ID errors

The Log Analytics PowerShell query command uses a workspace ID rather than the workspace name and resource group parameters used for discovery. Resolve the workspace first, pass its CustomerId to the query cmdlet, and keep data queries distinct from table management APIs.

The lesson is that **querying log data, identifying a workspace and enumerating configured tables are three different operations**. The PowerShell parameters and Azure APIs reflect that separation.

The examples below use a fictional workspace. Replace the placeholder resource names only when running them in an environment where you have permission.

## Step 1 — Resolve the workspace and Azure context

Start by checking the subscription before looking up a workspace. There may be several workspaces with similar names across resource groups and subscriptions.

powershell

```
Connect-AzAccount

# Use the intended subscription, not whichever context was last selected.
Set-AzContext -Subscription "00000000-0000-0000-0000-000000000000"

$workspace = Get-AzOperationalInsightsWorkspace `
    -ResourceGroupName "rg-security-logs" `
    -Name "la-security-workspace"

$workspace | Select-Object Name, ResourceGroupName, CustomerId, ResourceId
```

`Name` identifies the workspace by its human-readable name. `ResourceId` identifies the ARM resource path. `CustomerId` is the workspace identifier used by the Log Analytics query API. They are related, but are not interchangeable.

If `$workspace` returns nothing, verify your subscription context, resource group and access permissions before debugging the query itself.

## Step 2 — Use the correct WorkspaceId parameter

This is **not** a valid parameter pattern for the query cmdlet:

powershell

```
# Incorrect: these parameters are for workspace discovery, not for the query.
Invoke-AzOperationalInsightsQuery `
    -WorkspaceName "la-security-workspace" `
    -ResourceGroupName "rg-security-logs" `
    -Query "Heartbeat | take 5"
```

The documented parameter is `-WorkspaceId`. Resolve the workspace first, then pass the `CustomerId`.

powershell

```
$query = @'
Heartbeat
| where TimeGenerated > ago(1d)
| summarize Events = count(), LatestEvent = max(TimeGenerated)
    by Computer
| order by Events desc
'@

$result = Invoke-AzOperationalInsightsQuery `
    -WorkspaceId $workspace.CustomerId `
    -Query $query `
    -ErrorAction Stop

$result.Results | Format-Table -AutoSize
```

This example queries `Heartbeat` only when the table exists and has available data. An empty result could mean no recent heartbeat records; an error about a missing table is a different problem. Confirm the actual table and retention settings rather than interpreting both outcomes as identical.

## Step 3 — Export structured CSV and JSON data

PowerShell objects display neatly on screen but that does not mean they automatically produce usable CSV or JSON. Export the result collection rather than formatted console output.

powershell

```
$rows = @($result.Results)

$rows | Export-Csv `
    -Path "./workspace-query-results.csv" `
    -NoTypeInformation -Encoding utf8

$rows | ConvertTo-Json -Depth 12 |
    Set-Content -Path "./workspace-query-results.json" -Encoding utf8

Write-Host "Exported $($rows.Count) rows"
```

When the query returns no records, test the files and their expected consumers. JSON from a zero-row collection may need a documented empty-array convention. For large outputs, follow paging, query limits and resource throttling rather than assuming one request exports the entire dataset.

## Step 4 — List tables through the management API

A command such as `.show tables` belongs to other Kusto management contexts. It is not a supported way to enumerate tables from the normal Log Analytics Logs query interface.

Similarly, the Log Analytics **query** endpoint supports a `/query` operation. Sending a request to a guessed `/tables` path under the workspace query endpoint is not equivalent to asking Azure Resource Manager for configured table resources.

Use the workspace **Tables** experience in the Azure portal or the Azure Resource Manager tables API for inventory. For example, Azure CLI can call a resource-scoped ARM endpoint:

powershell

```
# Illustrative ARM request: supply your real subscription and resource path.
$sub = "00000000-0000-0000-0000-000000000000"
$rg = "rg-security-logs"
$ws = "la-security-workspace"

$uri = "https://management.azure.com/subscriptions/$sub/" +
    "resourceGroups/$rg/providers/Microsoft.OperationalInsights/" +
    "workspaces/$ws/tables?api-version=2025-02-01"

az rest --method get --url $uri
```

Follow any `nextLink` returned by a paginated list operation. Inventory results may contain tables with no recent ingested data, which is exactly why you should not substitute a usage-only query for an inventory.

## Step 5 — Measure usage without guessing query activity

The `Usage` table can be useful for looking at ingestion over a period:

kusto

```
Usage
| where TimeGenerated > ago(14d)
| where IsBillable == true
| summarize VolumeGB = sum(Quantity) / 1000.0
    by DataType
| order by VolumeGB desc
```

This is a **usage estimate by data type**, not a list of every configured table, not an invoice, and not the last time an analyst queried a table. Check the workspace's current billing model, reporting semantics and retention when comparing this with invoices.

For actual query audit evidence, investigate `LAQueryLogs` only if that audit source has already been configured and retained. An absent query log cannot establish that a table was never used.

## Troubleshooting checklist

<table><thead><tr><th scope="col">Symptom</th><th scope="col">Likely check</th></tr></thead><tbody><tr><td><code>-WorkspaceName</code> parameter not found</td><td>Use <code>Get-AzOperationalInsightsWorkspace</code> first, then <code>-WorkspaceId $workspace.CustomerId</code></td></tr><tr><td>No workspace object returned</td><td>Confirm subscription, resource group, name and RBAC</td></tr><tr><td>KQL reports missing table</td><td>Check actual schema, ingestion and permissions</td></tr><tr><td><code>.show tables</code> fails in Logs</td><td>Use the portal Tables view or management API instead</td></tr><tr><td>Guessed <code>/tables</code> query API path fails</td><td>Separate query data-plane endpoints from ARM management endpoints</td></tr><tr><td>CSV/JSON export is empty</td><td>Inspect <code>$result.Results</code>, time range, table coverage and query limits</td></tr><tr><td>Usage shows zero for a configured table</td><td>Do not infer the table is absent or unnecessary</td></tr></tbody></table>

## Operational safeguards and next steps

Keep two inventories: (1) the **configured tables** from the management plane and (2) the **observed ingestion volumes** from the data plane. Then add a separate dependency assessment covering analytics rules, workbooks, hunting queries, playbooks, stored functions and compliance needs. This prevents the particularly risky shortcut of stopping telemetry simply because it appears quiet.

## Microsoft documentation

- [Invoke-AzOperationalInsightsQuery PowerShell reference](https://learn.microsoft.com/en-us/powershell/module/az.operationalinsights/invoke-azoperationalinsightsquery)
- [Get-AzOperationalInsightsWorkspace PowerShell reference](https://learn.microsoft.com/en-us/powershell/module/az.operationalinsights/get-azoperationalinsightsworkspace)
- [Manage tables in a Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/manage-logs-tables)
- [Azure Monitor Logs API overview](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/api/overview)

[← Browse more field notes](https://blog.threatintels.org/blog/index.html)
