Skip to content

Instantly share code, notes, and snippets.

@TheCloudScout
Last active September 23, 2026 12:21
Show Gist options
  • Select an option

  • Save TheCloudScout/ab4aae2ca77f61a963403c7301cbbbde to your computer and use it in GitHub Desktop.

Select an option

Save TheCloudScout/ab4aae2ca77f61a963403c7301cbbbde to your computer and use it in GitHub Desktop.
Export-LogAnalyticsHistory.ps1
#Requires -Version 7
<#
.SYNOPSIS
Export historical Log Analytics data to Azure Blob Storage with Azure Monitor "Export job (preview)",
one job per table, straight from Azure Cloud Shell (PowerShell).
.DESCRIPTION
There is no "clone workspace" button in Azure, but since 2026 there is an export job API that writes a
table's records for a time range to Blob Storage as gzip Parquet, partitioned per hour. This script wraps
that API so you can preserve a time window of a whole workspace (think legal hold, audit, forensics) with
a handful of commands. It was built for Cloud Shell, so nothing blocks or sleeps: every phase finishes in
seconds and can be re-run. The job manifest lives in $HOME and in the storage account (container
'export-work'), so a disposable Cloud Shell session cannot lose your job ids.
Phases, in order:
Check : context, token, export API, workspace identity, storage account, RBAC, diagnostic setting.
Prepare : creates the storage account if missing, switches on the workspace identity, tries the role
assignments and diagnostic setting, warns about tables whose retention is shorter than the
window, and PRINTS the commands an Owner must run for what your role cannot.
Submit : submits jobs for the next free slots (the service allows 5 concurrent). Re-run until done.
Status : refreshes and prints job status (plus LAJobLogs when the Jobs diagnostic category is on).
Retry : retries every job in Failed state (5 retries per job, within 7 days).
Cancel : cancels the running job(s) of the given -Tables (for a job stuck in Queued) and frees the
table for a fresh Submit. The canceled job is kept in canceled-jobs.json for the record.
Clean : drops manifest entries that never got a job id.
Size : BEFORE submitting: GB ingested (Usage), GB and rows still present, retention gaps and a cost
estimate per table in scope. AFTER: blobs and GB per container in the storage account.
Works with or without -Tables.
Verify : row counts workspace vs export, SHA-256 of every blob, manifests to 'evidence-manifest'.
Hold : legal hold (tag = CaseTag) on every evidence container. Only after Verify.
Permissions you need yourself: Log Analytics Reader on the workspace (the export action is a DATA action,
so Contributor or Owner alone is NOT enough), plus Contributor on the resource group for Prepare.
Role assignments and the lock need Owner or User Access Administrator; the script prints those commands.
Time window: pass -StartTime and -EndTime (UTC). Without them the last 365 days are exported, ending at
the top of the current hour. One job covers at most one year, so split longer periods into several runs.
Costs (West Europe list prices, 2026): the Search Jobs meter per GB scanned, the Data Export meter per GB
landed, plus blob storage. For tens of GB that is a few euros. The storage bill is a rounding error.
Docs: https://learn.microsoft.com/azure/azure-monitor/logs/export-job
.PARAMETER WorkspaceName
Log Analytics workspace to export from.
.PARAMETER WorkspaceResourceGroup
Resource group of the workspace.
.PARAMETER StorageAccountName
Destination storage account. Created by Prepare when it does not exist (StorageV2, Standard_GRS by
default, public endpoint enabled because the export service and Cloud Shell arrive over public Azure IPs).
.PARAMETER StorageResourceGroup
Resource group of the storage account. Defaults to the workspace resource group.
.PARAMETER SubscriptionId
Subscription of the workspace. Defaults to the current Azure context.
.PARAMETER TenantId
Tenant of the workspace. Defaults to the current Azure context.
.PARAMETER StartTime
Start of the window, UTC, inclusive. Default: EndTime minus 365 days.
.PARAMETER EndTime
End of the window, UTC, exclusive. Must be in the past. Default: top of the current hour.
.PARAMETER Tables
Tables to export. Default: every table that ingested data in the window according to the Usage table.
.PARAMETER MaxConcurrent
Concurrent jobs to keep running. The service limit is 5 per workspace.
.PARAMETER CaseTag
Legal hold tag (3-23 lowercase letters and digits) and value of the 'case' tag on the storage account.
.PARAMETER Phase
Which phase to run. See DESCRIPTION.
.EXAMPLE
./Export-LogAnalyticsHistory.ps1 -WorkspaceName law-prod -WorkspaceResourceGroup rg-security -StorageAccountName stlawevidence01 -Phase Check
.EXAMPLE
./Export-LogAnalyticsHistory.ps1 -WorkspaceName law-prod -WorkspaceResourceGroup rg-security -StorageAccountName stlawevidence01 -StartTime 2026-05-23 -EndTime 2026-08-24 -Phase Submit
.EXAMPLE
./Export-LogAnalyticsHistory.ps1 -WorkspaceName law-prod -WorkspaceResourceGroup rg-security -StorageAccountName stlawevidence01 -Tables SigninLogs,AuditLogs -Phase Submit
.NOTES
Written for Azure Cloud Shell (PowerShell). Runs locally too with the Az modules and Connect-AzAccount.
Preview API: field names and behaviour may change. Always finish with Verify before you trust the copy.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$WorkspaceName,
[Parameter(Mandatory)] [string]$WorkspaceResourceGroup,
[Parameter(Mandatory)] [string]$StorageAccountName,
[string]$StorageResourceGroup,
[string]$SubscriptionId,
[string]$TenantId,
[datetime]$StartTime,
[datetime]$EndTime,
[string[]]$Tables,
[ValidateSet('Check', 'Prepare', 'Submit', 'Status', 'Retry', 'Cancel', 'Clean', 'Size', 'Verify', 'Hold')]
[string]$Phase = 'Check',
[ValidateRange(1, 5)] [int]$MaxConcurrent = 5,
[string]$StorageSku = 'Standard_GRS',
[string]$Location,
[ValidatePattern('^[a-z0-9]{3,23}$')] [string]$CaseTag = ('laexport' + (Get-Date -Format 'yyyyMMdd')),
[string]$WorkDir,
# Used by -Phase Size for the cost estimate. Defaults are West Europe EUR list prices (Sept 2026):
# Search Jobs Scanned per GB, Log Analytics Data Export per GB landed, cool-tier blob storage per GB per month.
[double]$PriceScanPerGB = 0.0056,
[double]$PriceExportPerGB = 0.1116,
[double]$PriceStoragePerGBMonth = 0.0086,
[ValidateRange(1, 50)] [double]$CompressionRatio = 8 # scanned GB : gzip Parquet GB; observed 7 to 40 per table, ~12 overall
)
$ErrorActionPreference = 'Stop'
$env:SuppressAzurePowerShellBreakingChangeWarnings = 'true'
$apiVersion = '2025-06-01-preview'
#region time window --------------------------------------------------------------------------------
function ConvertTo-Utc([datetime]$d) {
# a bare "2026-05-23" has Kind Unspecified; treat it as UTC instead of the shell's local zone
if ($d.Kind -eq [DateTimeKind]::Unspecified) { return [datetime]::SpecifyKind($d, [DateTimeKind]::Utc) }
return $d.ToUniversalTime()
}
$nowUtc = [datetime]::UtcNow
$hourTop = [datetime]::new($nowUtc.Year, $nowUtc.Month, $nowUtc.Day, $nowUtc.Hour, 0, 0, [DateTimeKind]::Utc)
$EndTime = if ($PSBoundParameters.ContainsKey('EndTime')) { ConvertTo-Utc $EndTime } else { $hourTop }
if ($EndTime -gt $hourTop) { Write-Warning "EndTime must be in the past; clamped to $($hourTop.ToString('u'))"; $EndTime = $hourTop }
$StartTime = if ($PSBoundParameters.ContainsKey('StartTime')) { ConvertTo-Utc $StartTime } else { $EndTime.AddDays(-365) }
if ($StartTime -ge $EndTime) { throw "StartTime ($StartTime) must be before EndTime ($EndTime)" }
if (($EndTime - $StartTime).TotalDays -gt 366) { throw 'An export job covers at most one year. Split the period into several runs with -StartTime/-EndTime.' }
$startUtc = $StartTime.ToString('yyyy-MM-ddTHH:mm:ss')
$endUtc = $EndTime.ToString('yyyy-MM-ddTHH:mm:ss')
$kqlWindow = "between (datetime($startUtc) .. datetime($endUtc))"
$windowDays = [math]::Round(($EndTime - $StartTime).TotalDays, 1)
#endregion
#region context and resources ----------------------------------------------------------------------
$ctx = Get-AzContext
if (-not $ctx) { throw 'No Azure context. Cloud Shell signs you in automatically; locally run Connect-AzAccount first.' }
if ($SubscriptionId -and ($ctx.Subscription.Id -ne $SubscriptionId -or ($TenantId -and $ctx.Tenant.Id -ne $TenantId))) {
$p = @{ Subscription = $SubscriptionId }; if ($TenantId) { $p.Tenant = $TenantId }
Set-AzContext @p | Out-Null
$ctx = Get-AzContext
}
$SubscriptionId = $ctx.Subscription.Id
$TenantId = $ctx.Tenant.Id
Write-Host "Context : $($ctx.Account.Id) / tenant $TenantId / sub $($ctx.Subscription.Name)" -ForegroundColor Cyan
$ws = Get-AzOperationalInsightsWorkspace -ResourceGroupName $WorkspaceResourceGroup -Name $WorkspaceName
$wsArmId = $ws.ResourceId
$WorkspaceId = [string]$ws.CustomerId
if (-not $Location) { $Location = $ws.Location }
if (-not $StorageResourceGroup) { $StorageResourceGroup = $WorkspaceResourceGroup }
Write-Host "Workspace: $WorkspaceName ($WorkspaceId, $($ws.Location), retention $($ws.retentionInDays) days)" -ForegroundColor Cyan
Write-Host "Window : $startUtc .. $endUtc UTC ($windowDays days)" -ForegroundColor Cyan
$storageArmId = "/subscriptions/$SubscriptionId/resourceGroups/$StorageResourceGroup/providers/Microsoft.Storage/storageAccounts/$StorageAccountName"
$jobsBaseUrl = "https://api.loganalytics.io/v2/subscriptions/$SubscriptionId/resourcegroups/$WorkspaceResourceGroup/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/jobs/export"
if (-not $WorkDir) { $WorkDir = Join-Path $HOME 'la-export' $WorkspaceName }
New-Item -ItemType Directory -Path $WorkDir -Force | Out-Null
$manifestPath = Join-Path $WorkDir 'export-jobs.json'
$existingSa = Get-AzStorageAccount -ErrorAction SilentlyContinue | Where-Object StorageAccountName -eq $StorageAccountName | Select-Object -First 1
if ($existingSa) {
$StorageResourceGroup = $existingSa.ResourceGroupName
$storageArmId = $existingSa.Id
$netDefault = $existingSa.NetworkRuleSet.DefaultAction
Write-Host "Storage : $StorageAccountName in $StorageResourceGroup ($($existingSa.Kind) / $($existingSa.Sku.Name), $($existingSa.PrimaryLocation); public access $($existingSa.PublicNetworkAccess), default action $netDefault)" -ForegroundColor Cyan
if ($existingSa.Sku.Name -like 'Premium*') {
Write-Host ' [!!] Premium SKU. The Log Analytics export pipeline documents Premium as unsupported, and Premium has no cool tier.' -ForegroundColor Yellow
Write-Host ' Use a Standard StorageV2 account instead.' -ForegroundColor Yellow
}
if ($existingSa.PublicNetworkAccess -eq 'Disabled' -or $netDefault -eq 'Deny') {
Write-Host ' [!!] Public endpoint restricted. Cloud Shell and the export service both arrive over public Azure IPs and will be' -ForegroundColor Yellow
Write-Host ' refused with AuthorizationFailure. Set Networking to "Enabled from all networks" during the export, re-restrict after.' -ForegroundColor Yellow
}
}
else {
Write-Host "Storage : $StorageAccountName not found in this subscription. -Phase Prepare creates it in $StorageResourceGroup (StorageV2 / $StorageSku, $Location)." -ForegroundColor Yellow
}
#endregion
#region helpers ------------------------------------------------------------------------------------
function Get-LaToken {
$t = Get-AzAccessToken -ResourceUrl 'https://api.loganalytics.io'
if ($t.Token -is [securestring]) { return (ConvertFrom-SecureString -SecureString $t.Token -AsPlainText) }
return $t.Token
}
function Invoke-LaApi {
param([ValidateSet('GET', 'POST')][string]$Method, [string]$Path, [hashtable]$Body)
$params = @{
Method = $Method
Uri = "$jobsBaseUrl$Path`?api-version=$apiVersion"
Headers = @{ Authorization = "Bearer $(Get-LaToken)" }
ContentType = 'application/json'
SkipHttpErrorCheck = $true
}
if ($Body) { $params.Body = ($Body | ConvertTo-Json -Depth 5) }
$r = Invoke-WebRequest @params
$parsed = $null
if ($r.Content) { try { $parsed = $r.Content | ConvertFrom-Json } catch { $parsed = $r.Content } }
$ids = @('x-ms-request-id', 'x-ms-correlation-request-id', 'x-ms-activity-id') | ForEach-Object { if ($r.Headers[$_]) { "$_=$($r.Headers[$_] -join ',')" } }
return [pscustomobject]@{ Status = [int]$r.StatusCode; Body = $parsed; RequestIds = ($ids -join ' ') }
}
function Invoke-Kql([string]$Query, [int]$Days = 400) {
return (Invoke-AzOperationalInsightsQuery -WorkspaceId $WorkspaceId -Query $Query -Timespan (New-TimeSpan -Days $Days)).Results
}
function Get-StorageCtx { (Get-AzStorageAccount -ResourceGroupName $StorageResourceGroup -Name $StorageAccountName).Context }
function Get-ContainerName([string]$Table) {
# container names: 3-63 chars, lowercase letters, digits, hyphens
$n = 'law-' + (($Table.ToLowerInvariant() -replace '[^a-z0-9]', '-').Trim('-'))
return $n.Substring(0, [Math]::Min(63, $n.Length))
}
function Get-Manifest {
try {
$c = Get-StorageCtx
if (Get-AzStorageBlob -Container 'export-work' -Blob 'export-jobs.json' -Context $c -ErrorAction SilentlyContinue) {
Get-AzStorageBlobContent -Container 'export-work' -Blob 'export-jobs.json' -Destination $manifestPath -Context $c -Force | Out-Null
}
} catch { Write-Verbose "no blob manifest yet: $($_.Exception.Message)" }
if (Test-Path $manifestPath) { return @(Get-Content $manifestPath -Raw | ConvertFrom-Json) }
return @()
}
function Save-Manifest([object[]]$Jobs) {
ConvertTo-Json -InputObject @($Jobs) -Depth 5 | Set-Content -Path $manifestPath -Encoding utf8
try {
$c = Get-StorageCtx
New-AzStorageContainer -Name 'export-work' -Context $c -ErrorAction SilentlyContinue | Out-Null
Set-AzStorageBlobContent -File $manifestPath -Container 'export-work' -Blob 'export-jobs.json' -Context $c -Force | Out-Null
} catch { Write-Warning "manifest saved locally only ($manifestPath): $($_.Exception.Message)" }
}
function Test-Terminal([string]$Status) {
return $Status -notin @('Submitted', 'InProgress', 'Started', 'Accepted', 'Queued', 'Running', 'RetrySubmitted', $null, '')
}
# the status API reports 'Completed' for a finished job; LAJobLogs says 'Succeeded'. Accept both.
$successStates = @('Completed', 'Succeeded')
function Update-Status([object[]]$Jobs) {
foreach ($j in $Jobs | Where-Object { $_.jobId }) {
$r = Invoke-LaApi -Method GET -Path "/$($j.jobId)/status"
if ($r.Status -eq 200) {
$j.status = $r.Body.jobStatus
$j.progress = $r.Body.resultStatistics.progressPercentage
$j.resultCount = $r.Body.resultStatistics.resultCount
$j.scannedGB = $r.Body.resultStatistics.scannedGigabytes
}
else { $j.status = "StatusHttp$($r.Status)" }
$j.lastChecked = (Get-Date).ToUniversalTime().ToString('o')
}
if ($Jobs.Count) { Save-Manifest $Jobs }
return $Jobs
}
function Show-Jobs([object[]]$Jobs) {
$Jobs | Sort-Object status, table |
Format-Table table, status,
@{n = 'progress%'; e = { if ($null -ne $_.progress) { [math]::Round([double]$_.progress, 1) } } },
resultCount,
@{n = 'scannedGB'; e = { if ($null -ne $_.scannedGB) { [math]::Round([double]$_.scannedGB, 3) } } },
retries, jobId -AutoSize | Out-String -Width 200 | Write-Host
}
function Get-WindowTables {
# explicit list wins; otherwise every table that ingested data in the window according to Usage
if ($Tables) { return @($Tables | ForEach-Object { [pscustomobject]@{ DataType = $_; GB = $null } }) }
$usageFrom = (Invoke-Kql 'Usage | summarize Earliest = min(TimeGenerated)' | Select-Object -First 1).Earliest
if ($usageFrom -and ([datetime]$usageFrom).ToUniversalTime() -gt $StartTime.AddDays(1)) {
Write-Warning "The Usage table only reaches back to $usageFrom, so tables that stopped ingesting before that date are not discovered. Pass -Tables explicitly if you know of any."
}
$rows = Invoke-Kql "Usage | where TimeGenerated $kqlWindow | where Quantity > 0 | summarize GB = round(sum(Quantity)/1024, 3) by DataType | order by GB desc"
return @($rows | Select-Object DataType, GB)
}
#endregion helpers ----------------------------------------------------------------------------------
switch ($Phase) {
'Check' {
$ok = { param($m) Write-Host " [ok] $m" -ForegroundColor Green }
$bad = { param($m) Write-Host " [!!] $m" -ForegroundColor Yellow }
Write-Host "`nToken for api.loganalytics.io" -ForegroundColor Cyan
try { $null = Get-LaToken; & $ok 'token acquired' }
catch { & $bad "cannot get a Log Analytics API token: $($_.Exception.Message)"; break }
Write-Host 'Query permission on the workspace' -ForegroundColor Cyan
try { $null = Invoke-Kql 'print ok = 1' -Days 1; & $ok 'a query runs, so you can read the workspace' }
catch { & $bad "query failed: $($_.Exception.Message)" }
Write-Host 'Export job API' -ForegroundColor Cyan
$probe = Invoke-LaApi -Method GET -Path '/00000000-0000-0000-0000-000000000000/status'
$probeBody = if ($probe.Body) { $probe.Body | ConvertTo-Json -Compress -Depth 5 } else { '(empty body)' }
switch ($probe.Status) {
{ $_ -in 400, 404, 500 } { & $ok "API reachable, token accepted (HTTP $_ for a dummy job id is the expected answer)" }
401 { & $bad "HTTP 401, token not accepted. Body: $probeBody" }
403 { & $bad "HTTP 403 Forbidden. Body: $probeBody $($probe.RequestIds)"
Write-Host ' The export action (Microsoft.OperationalInsights/workspaces/jobs/export/action) is a DATA action. Contributor and' -ForegroundColor Yellow
Write-Host ' Owner carry no data actions, Log Analytics Reader and Log Analytics Contributor do. Assign Log Analytics Reader' -ForegroundColor Yellow
Write-Host ' to your own account on the workspace, wait ~5 minutes, re-run.' -ForegroundColor Yellow }
default { & $bad "unexpected HTTP $($probe.Status). Body: $probeBody" }
}
Write-Host 'Workspace identity' -ForegroundColor Cyan
$wsRaw = (Invoke-AzRestMethod -Method GET -Path "$wsArmId`?api-version=2025-07-01").Content | ConvertFrom-Json
$principalId = $wsRaw.identity.principalId
if ($principalId) { & $ok "system-assigned identity present: $principalId" } else { & $bad 'no system-assigned managed identity (Prepare adds it)' }
Write-Host "Storage account $StorageAccountName" -ForegroundColor Cyan
if ($existingSa) {
& $ok "exists ($($existingSa.Kind) / $($existingSa.Sku.Name), $($existingSa.PrimaryLocation))"
try { $null = Get-AzStorageContainer -Context (Get-StorageCtx) -MaxCount 1 -ErrorAction Stop; & $ok 'blob endpoint reachable from this session' }
catch {
if ($_.Exception.Message -match 'AuthorizationFailure|not authorized to perform this operation') { & $bad 'blob endpoint refused with AuthorizationFailure: the storage firewall blocks this session and will block the export service too' }
else { & $bad "blob endpoint probe failed: $($_.Exception.Message)" }
}
if ($principalId) {
$miRoles = @(Get-AzRoleAssignment -ObjectId $principalId -Scope $storageArmId -ErrorAction SilentlyContinue | Select-Object -ExpandProperty RoleDefinitionName -Unique)
Write-Host " identity roles at storage scope (incl. inherited): $(if ($miRoles) { $miRoles -join ', ' } else { 'none' })"
if ($miRoles | Where-Object { $_ -in 'Storage Blob Data Contributor', 'Storage Blob Data Owner' }) { & $ok 'identity can write blobs' } else { & $bad 'identity lacks Storage Blob Data Contributor (needs Owner/UAA to assign)' }
if ($miRoles | Where-Object { $_ -in 'Log Analytics Reader', 'Reader', 'Contributor', 'Owner', 'Storage Account Contributor' }) { & $ok 'identity can read the storage account resource' }
else { & $bad 'identity lacks Microsoft.Storage/storageAccounts/read on the account (Log Analytics Reader per the doc, plain Reader works too)' }
}
}
else { & $bad 'does not exist yet (Prepare creates it)' }
Write-Host 'Diagnostic setting (Jobs category, for LAJobLogs)' -ForegroundColor Cyan
$diag = Get-AzDiagnosticSetting -ResourceId $wsArmId -ErrorAction SilentlyContinue | Where-Object { ($_.Log | Where-Object { $_.Category -eq 'Jobs' -and $_.Enabled }) }
foreach ($d in $diag) {
if ($d.WorkspaceId -and ($d.WorkspaceId -ieq $wsArmId)) { & $ok "setting '$($d.Name)' sends Jobs to this workspace, LAJobLogs will fill" }
else { & $bad "setting '$($d.Name)' sends Jobs elsewhere; LAJobLogs here stays empty unless Prepare adds one" }
}
if (-not $diag) { & $bad 'no diagnostic setting with the Jobs category (Prepare adds it)' }
Write-Host 'Lock' -ForegroundColor Cyan
if (Get-AzResourceLock -ResourceGroupName $WorkspaceResourceGroup -ResourceName $WorkspaceName -ResourceType 'Microsoft.OperationalInsights/workspaces' -ErrorAction SilentlyContinue) { & $ok 'workspace has a lock' }
else { & $bad 'no lock on the workspace (Prepare tries; needs Owner/UAA)' }
}
'Prepare' {
$forAdmin = [System.Collections.Generic.List[string]]::new()
Write-Host "`n[1/6] Retention of the tables in scope versus the window" -ForegroundColor Cyan
$daysBack = [math]::Ceiling(($nowUtc - $StartTime).TotalDays)
$scope = @((Get-WindowTables).DataType)
$short = @(Get-AzOperationalInsightsTable -ResourceGroupName $WorkspaceResourceGroup -WorkspaceName $WorkspaceName | Where-Object { $_.Name -in $scope -and $_.TotalRetentionInDays -lt $daysBack })
if ($short) {
foreach ($t in $short) {
Write-Warning " $($t.Name): total retention $($t.TotalRetentionInDays) days, but the window reaches back $daysBack days. Data before $($nowUtc.AddDays(-$t.TotalRetentionInDays).ToString('yyyy-MM-dd')) is already gone and the rest keeps ageing out."
$forAdmin.Add("Update-AzOperationalInsightsTable -ResourceGroupName '$WorkspaceResourceGroup' -WorkspaceName '$WorkspaceName' -TableName '$($t.Name)' -TotalRetentionInDays $daysBack # stops the loss; Contributor on the workspace can run this")
}
}
else { Write-Host " all $($scope.Count) tables keep at least $daysBack days, the whole window is still there" -ForegroundColor Green }
Write-Host "[2/6] Storage account $StorageAccountName" -ForegroundColor Cyan
try {
if (-not $existingSa) {
$avail = Get-AzStorageAccountNameAvailability -Name $StorageAccountName
if (-not $avail.NameAvailable) { throw "name '$StorageAccountName' not available: $($avail.Message)" }
Write-Host " creating $StorageAccountName in $StorageResourceGroup ($Location, StorageV2, $StorageSku, cool tier, public endpoint on, no anonymous access, TLS 1.2)"
$newSa = New-AzStorageAccount -ResourceGroupName $StorageResourceGroup -Name $StorageAccountName -Location $Location `
-SkuName $StorageSku -Kind StorageV2 -AccessTier Cool -AllowBlobPublicAccess $false -MinimumTlsVersion TLS1_2 `
-PublicNetworkAccess Enabled -AllowSharedKeyAccess $true -EnableHttpsTrafficOnly $true `
-Tag @{ purpose = 'log-analytics-export'; case = $CaseTag; workspace = $WorkspaceName; window = "$startUtc..$endUtc" }
for ($i = 0; $i -lt 12 -and $newSa.ProvisioningState -ne 'Succeeded'; $i++) {
Start-Sleep -Seconds 5
$newSa = Get-AzStorageAccount -ResourceGroupName $StorageResourceGroup -Name $StorageAccountName
}
$existingSa = $newSa; $storageArmId = $newSa.Id
Write-Host " created. Resource id: $storageArmId" -ForegroundColor Green
}
else { Write-Host ' exists, kept as is' }
Update-AzStorageBlobServiceProperty -ResourceGroupName $StorageResourceGroup -StorageAccountName $StorageAccountName -IsVersioningEnabled $true | Out-Null
Enable-AzStorageBlobDeleteRetentionPolicy -ResourceGroupName $StorageResourceGroup -StorageAccountName $StorageAccountName -RetentionDays 30 | Out-Null
Enable-AzStorageContainerDeleteRetentionPolicy -ResourceGroupName $StorageResourceGroup -StorageAccountName $StorageAccountName -RetentionDays 30 | Out-Null
Write-Host ' versioning + 30d soft delete (blobs and containers) on' -ForegroundColor Green
} catch { Write-Warning $_.Exception.Message }
Write-Host '[3/6] System-assigned managed identity on the workspace' -ForegroundColor Cyan
$principalId = $null
try {
$resp = Invoke-AzRestMethod -Method PATCH -Path "$wsArmId`?api-version=2025-07-01" -Payload (@{ identity = @{ type = 'SystemAssigned' } } | ConvertTo-Json)
if ($resp.StatusCode -ge 300) { throw "HTTP $($resp.StatusCode): $($resp.Content)" }
$principalId = ($resp.Content | ConvertFrom-Json).identity.principalId
if (-not $principalId) {
Start-Sleep -Seconds 10
$principalId = ((Invoke-AzRestMethod -Method GET -Path "$wsArmId`?api-version=2025-07-01").Content | ConvertFrom-Json).identity.principalId
}
Write-Host " principalId = $principalId" -ForegroundColor Green
} catch { Write-Warning $_.Exception.Message }
Write-Host '[4/6] Role assignments for the identity on the storage account' -ForegroundColor Cyan
$miRoles = @()
if ($principalId) { $miRoles = @(Get-AzRoleAssignment -ObjectId $principalId -Scope $storageArmId -ErrorAction SilentlyContinue | Select-Object -ExpandProperty RoleDefinitionName -Unique) }
$needed = @(
@{ Role = 'Storage Blob Data Contributor'; SatisfiedBy = 'Storage Blob Data Contributor', 'Storage Blob Data Owner' }
@{ Role = 'Log Analytics Reader'; SatisfiedBy = 'Log Analytics Reader', 'Reader', 'Contributor', 'Owner', 'Storage Account Contributor' }
)
foreach ($n in $needed) {
$cmd = "New-AzRoleAssignment -ObjectId $principalId -RoleDefinitionName '$($n.Role)' -Scope '$storageArmId'"
if ($miRoles | Where-Object { $_ -in $n.SatisfiedBy }) { Write-Host " $($n.Role) : already satisfied by [$(($miRoles | Where-Object { $_ -in $n.SatisfiedBy }) -join ', ')]" -ForegroundColor Green; continue }
try {
if (-not $principalId) { throw 'no principalId' }
New-AzRoleAssignment -ObjectId $principalId -RoleDefinitionName $n.Role -Scope $storageArmId -ErrorAction Stop | Out-Null
Write-Host " $($n.Role) : assigned" -ForegroundColor Green
} catch { Write-Warning " $($n.Role) : $($_.Exception.Message)"; $forAdmin.Add($cmd) }
}
Write-Host '[5/6] Diagnostic setting Jobs + Audit -> same workspace' -ForegroundColor Cyan
try {
$existing = Get-AzDiagnosticSetting -ResourceId $wsArmId -ErrorAction SilentlyContinue | Where-Object { $_.WorkspaceId -ieq $wsArmId }
$covered = @($existing | ForEach-Object { $_.Log | Where-Object Enabled | Select-Object -ExpandProperty Category }) | Select-Object -Unique
$missing = @('Jobs', 'Audit' | Where-Object { $_ -notin $covered })
if (-not $missing) { Write-Host " already covered by [$($existing.Name -join ', ')]" -ForegroundColor Green }
else {
$logs = @($missing | ForEach-Object { New-AzDiagnosticSettingLogSettingsObject -Category $_ -Enabled $true })
New-AzDiagnosticSetting -Name 'export-jobs-audit' -ResourceId $wsArmId -WorkspaceId $wsArmId -Log $logs -ErrorAction Stop | Out-Null
Write-Host " added categories: $($missing -join ', ')" -ForegroundColor Green
}
} catch { Write-Warning $_.Exception.Message }
Write-Host '[6/6] CanNotDelete lock on the workspace (ReadOnly would break Sentinel writes, so not that)' -ForegroundColor Cyan
$lockCmd = "New-AzResourceLock -LockName 'export-hold-no-delete' -LockLevel CanNotDelete -ResourceGroupName '$WorkspaceResourceGroup' -ResourceName '$WorkspaceName' -ResourceType 'Microsoft.OperationalInsights/workspaces' -LockNotes 'Data preservation $CaseTag' -Force"
try { Invoke-Expression $lockCmd | Out-Null; Write-Host ' done' -ForegroundColor Green }
catch { Write-Warning $_.Exception.Message; $forAdmin.Add($lockCmd) }
if ($forAdmin.Count) {
Write-Host "`nYour role could not do the following. Hand these lines to someone with Owner or User Access Administrator:" -ForegroundColor Yellow
$forAdmin | ForEach-Object { Write-Host " $_" }
}
else { Write-Host "`nPrepare complete. Give RBAC ~5 minutes to propagate, then run -Phase Submit." -ForegroundColor Green }
}
'Submit' {
if (-not $existingSa) { throw "storage account $StorageAccountName does not exist. Run -Phase Prepare first." }
$scope = Get-WindowTables
$jobs = Update-Status (Get-Manifest)
$active = @($jobs | Where-Object { $_.jobId -and -not (Test-Terminal $_.status) }).Count
$slots = [Math]::Max(0, $MaxConcurrent - $active)
$done = @($jobs | Where-Object { $_.jobId -and $_.status -ne 'Canceled' }).table
$todo = @($scope | Where-Object { $_.DataType -notin $done })
if (-not $jobs) {
Write-Host "`nTables in scope ($($scope.Count)), GB ingested in the window according to Usage:" -ForegroundColor Cyan
$scope | Format-Table DataType, GB -AutoSize | Out-String | Write-Host
}
Write-Host "$active active, $slots free slot(s), $($todo.Count) table(s) still to submit" -ForegroundColor Cyan
foreach ($t in ($todo | Select-Object -First $slots)) {
$table = $t.DataType
$container = Get-ContainerName $table
$body = @{
startTime = $startUtc
endTime = $endUtc
query = $table
destinationStorageAccounts = @($storageArmId)
containerName = $container
outputDataFormat = 'Parquet'
dateTimeFormat = 'year=yyyy/month=MM/day=dd/hour=HH'
}
$r = Invoke-LaApi -Method POST -Path '' -Body $body
$jobs = @($jobs | Where-Object { $_.table -ne $table })
if ($r.Status -in 200, 201, 202 -and $r.Body.operationId) {
$jobs += [pscustomobject]@{
table = $table; estimatedGB = $t.GB; container = $container; jobId = $r.Body.operationId
submittedUtc = (Get-Date).ToUniversalTime().ToString('o'); startTime = $startUtc; endTime = $endUtc
status = 'Submitted'; progress = $null; resultCount = $null; scannedGB = $null; lastChecked = $null; retries = 0; error = $null
}
Write-Host " submitted $table -> $container jobId=$($r.Body.operationId)" -ForegroundColor Green
}
else {
$err = ($r.Body | ConvertTo-Json -Compress -Depth 5)
$jobs += [pscustomobject]@{
table = $table; estimatedGB = $t.GB; container = $container; jobId = $null; submittedUtc = (Get-Date).ToUniversalTime().ToString('o')
startTime = $startUtc; endTime = $endUtc; status = 'SubmitFailed'; progress = $null; resultCount = $null
scannedGB = $null; lastChecked = $null; retries = 0; error = "HTTP $($r.Status) $err $($r.RequestIds)"
}
Write-Warning " $table : HTTP $($r.Status) $err $($r.RequestIds)"
if ($r.Status -eq 403) { Write-Warning ' 403 on submit: your account needs Log Analytics Reader on the workspace (the export action is a data action). Stopping this run.'; Save-Manifest $jobs; break }
}
Save-Manifest $jobs
}
$remaining = $todo.Count - [Math]::Min($slots, $todo.Count)
if ($remaining -gt 0) { Write-Host "`n$remaining table(s) waiting for a free slot. Run -Phase Submit again in a while." -ForegroundColor Yellow }
elseif ($todo.Count -eq 0) { Write-Host "`nAll tables submitted. Follow with -Phase Status." -ForegroundColor Green }
if ($jobs) { Show-Jobs $jobs }
}
'Status' {
$jobs = Update-Status (Get-Manifest)
if ($jobs) { Show-Jobs $jobs } else { Write-Host 'no jobs in the manifest yet' }
try {
$rows = Invoke-Kql 'LAJobLogs | where JobType == "Export" | summarize arg_max(TimeGenerated, Status, ResultsRecordCount, ResultsGB, Message) by JobId, SourceTable | order by SourceTable asc' -Days 14
Write-Host 'LAJobLogs:' -ForegroundColor Cyan
$rows | Format-Table SourceTable, Status, ResultsRecordCount, ResultsGB, Message -AutoSize | Out-String -Width 200 | Write-Host
} catch { Write-Warning "LAJobLogs not available: $($_.Exception.Message)" }
}
'Retry' {
$jobs = Update-Status (Get-Manifest)
foreach ($j in ($jobs | Where-Object { $_.status -eq 'Failed' })) {
if ($j.retries -ge 5) { Write-Warning "$($j.table): 5 retries used; submit a fresh job instead"; continue }
$r = Invoke-LaApi -Method POST -Path "/$($j.jobId)/retry"
if ($r.Status -in 200, 202) { $j.retries++; $j.status = 'RetrySubmitted'; Write-Host " retried $($j.table) ($($j.retries)/5)" -ForegroundColor Green }
else { Write-Warning " $($j.table): HTTP $($r.Status) $($r.Body | ConvertTo-Json -Compress -Depth 5) $($r.RequestIds)" }
}
Save-Manifest $jobs
if ($jobs) { Show-Jobs $jobs }
}
'Cancel' {
if (-not $Tables) { throw 'Cancel needs -Tables <name,...>. It refuses to cancel every job at once.' }
$jobs = Update-Status (Get-Manifest)
$canceledPath = Join-Path $WorkDir 'canceled-jobs.json'
$history = if (Test-Path $canceledPath) { @(Get-Content $canceledPath -Raw | ConvertFrom-Json) } else { @() }
foreach ($table in $Tables) {
$j = $jobs | Where-Object { $_.table -eq $table -and $_.jobId } | Select-Object -First 1
if (-not $j) { Write-Warning "$table : no job in the manifest"; continue }
if (Test-Terminal $j.status) { Write-Warning "$table : job is already $($j.status), nothing to cancel"; continue }
$r = Invoke-LaApi -Method POST -Path "/$($j.jobId)/cancel"
if ($r.Status -in 200, 202) {
$j.status = 'Canceled'
$j | Add-Member -NotePropertyName canceledUtc -NotePropertyValue ((Get-Date).ToUniversalTime().ToString('o')) -Force
$history += $j
$jobs = @($jobs | Where-Object { $_.jobId -ne $j.jobId })
Write-Host " canceled $table (jobId $($j.jobId)). Kept in canceled-jobs.json; the table is free for a fresh Submit." -ForegroundColor Green
if ([double]$j.progress -gt 0) {
Write-Warning " it had written partial output. Remove it before Hold so the container holds one complete job only:"
Write-Warning " Get-AzStorageBlob -Container $($j.container) -Prefix 'workspaceId/$WorkspaceId/jobId/$($j.jobId)/' -Context (Get-StorageCtx) | Remove-AzStorageBlob"
}
}
else { Write-Warning " $table : HTTP $($r.Status) $($r.Body | ConvertTo-Json -Compress -Depth 5) $($r.RequestIds)" }
}
ConvertTo-Json -InputObject @($history) -Depth 5 | Set-Content $canceledPath -Encoding utf8
try { Set-AzStorageBlobContent -File $canceledPath -Container 'export-work' -Blob 'canceled-jobs.json' -Context (Get-StorageCtx) -Force | Out-Null } catch { }
Save-Manifest $jobs
Write-Host "`nResubmit with: -Phase Submit -Tables $($Tables -join ',')" -ForegroundColor Cyan
}
'Clean' {
$jobs = Get-Manifest
$drop = @($jobs | Where-Object { -not $_.jobId -or $_.status -eq 'SubmitFailed' })
$keep = @($jobs | Where-Object { $_.jobId -and $_.status -ne 'SubmitFailed' })
Save-Manifest $keep
if ($drop) { Write-Host "`nremoved $($drop.Count) entrie(s) that never got a job id: $($drop.table -join ', ')" -ForegroundColor Green } else { Write-Host "`nnothing to remove" -ForegroundColor Green }
Write-Host "$($keep.Count) job(s) kept in the manifest (local and blob copy updated)."
if ($keep) { Show-Jobs $keep }
}
'Size' {
# ---- part 1: what the window holds, straight from the workspace (works before any job exists) ----
$scope = @((Get-WindowTables).DataType)
$daysBack = [math]::Ceiling(($nowUtc - $StartTime).TotalDays)
$usage = @{}
Invoke-Kql "Usage | where TimeGenerated $kqlWindow | where Quantity > 0 | summarize GB = round(sum(Quantity)/1024, 3) by DataType" |
ForEach-Object { $usage[$_.DataType] = [double]$_.GB }
$retention = @{}
Get-AzOperationalInsightsTable -ResourceGroupName $WorkspaceResourceGroup -WorkspaceName $WorkspaceName |
ForEach-Object { $retention[$_.Name] = $_.TotalRetentionInDays }
Write-Host "`nEstimate for $startUtc .. $endUtc UTC ($windowDays days), $($scope.Count) table(s). Querying each table for what is still present..." -ForegroundColor Cyan
$est = foreach ($table in $scope) {
$present = $null
try { $present = Invoke-Kql "$table | where TimeGenerated $kqlWindow | summarize Rows = count(), GB = round(sum(_BilledSize)/1024/1024/1024, 3)" | Select-Object -First 1 } catch { }
$ret = $retention[$table]
$note = if ($null -eq $ret) { 'table not in workspace' }
elseif ($ret -lt $daysBack) { "partial: keeps $ret d, window reaches back $daysBack d" }
else { '' }
[pscustomobject]@{
Table = $table
IngestedGB = $usage[$table]
PresentGB = if ($present) { [double]$present.GB } else { $null }
PresentRows = if ($present) { [long]$present.Rows } else { $null }
RetentionDays = $ret
Note = $note
}
}
$est | Sort-Object PresentGB -Descending | Format-Table -AutoSize | Out-String -Width 200 | Write-Host
$ingested = [math]::Round(($est | Measure-Object IngestedGB -Sum).Sum, 2)
$presentGB = [math]::Round(($est | Measure-Object PresentGB -Sum).Sum, 2)
$presentRows = ($est | Measure-Object PresentRows -Sum).Sum
$storeGB = [math]::Round($presentGB / $CompressionRatio, 2)
Write-Host ("Ingested in window (Usage): {0} GB. Still present and exportable: {1} GB, {2:N0} rows." -f $ingested, $presentGB, $presentRows) -ForegroundColor Green
Write-Host ("Expected in storage: ~{0} GB as gzip Parquet at {1}:1 (tune with -CompressionRatio)." -f $storeGB, $CompressionRatio)
# scan meter bills GB scanned in the workspace; export meter bills GB landed (compressed) in storage
Write-Host ("Estimated cost: scan {0:N2} + export {1:N2} = {2:N2} one-off, storage ~{3:N2} per month (list prices, override with -Price* parameters)." -f `
($presentGB * $PriceScanPerGB), ($storeGB * $PriceExportPerGB), ($presentGB * $PriceScanPerGB + $storeGB * $PriceExportPerGB), ($storeGB * $PriceStoragePerGBMonth))
if ($ingested -gt $presentGB + 0.5) { Write-Warning ("{0} GB that was ingested in the window is no longer in the workspace (retention). The export can only contain what is present." -f [math]::Round($ingested - $presentGB, 2)) }
# ---- part 2: what is actually in the storage account, if it exists ----
if (-not $existingSa) { Write-Host "`nStorage account $StorageAccountName does not exist yet, nothing in storage to measure." -ForegroundColor Yellow; break }
$c = Get-StorageCtx
$wanted = if ($Tables) { @($Tables | ForEach-Object { Get-ContainerName $_ }) } else { $null }
$containers = @(Get-AzStorageContainer -Context $c | Where-Object { -not $wanted -or $_.Name -in $wanted })
if (-not $containers) { Write-Host "`nNo matching containers in $StorageAccountName yet." -ForegroundColor Yellow; break }
Write-Host "`nIn storage now (current blob versions only):" -ForegroundColor Cyan
$rows = foreach ($cont in $containers) {
$blobs = @(Get-AzStorageBlob -Container $cont.Name -Context $c)
$bytes = ($blobs | Measure-Object Length -Sum).Sum
[pscustomobject]@{ Container = $cont.Name; Blobs = $blobs.Count; GB = [math]::Round(($bytes / 1GB), 3) }
}
$rows | Sort-Object GB -Descending | Format-Table -AutoSize | Out-String | Write-Host
$totalGB = [math]::Round(($rows | Measure-Object GB -Sum).Sum, 2)
$totalBlobs = ($rows | Measure-Object Blobs -Sum).Sum
Write-Host "Total: $totalGB GB in $totalBlobs blobs across $($rows.Count) container(s) ($($existingSa.Sku.Name), access tier $($existingSa.AccessTier))" -ForegroundColor Green
if ($presentGB -gt 0 -and $totalGB -gt 0) { Write-Host ("Observed compression so far: {0}:1 against the present GB (partial while jobs run)." -f [math]::Round($presentGB / $totalGB, 1)) }
try {
$m = Get-AzMetric -ResourceId "$storageArmId/blobServices/default" -MetricName BlobCapacity -TimeGrain 01:00:00 `
-StartTime (Get-Date).AddHours(-6) -EndTime (Get-Date) -AggregationType Average -WarningAction SilentlyContinue
$last = ($m.Data | Where-Object { $_.Average } | Select-Object -Last 1)
if ($last) { Write-Host "BlobCapacity metric at $($last.TimeStamp.ToString('u')): $([math]::Round($last.Average / 1GB, 2)) GB for the whole account (hourly, lags up to an hour, includes versions and soft-deleted blobs)" }
} catch { Write-Verbose "metric not available: $($_.Exception.Message)" }
}
'Verify' {
if (-not $existingSa) { throw "storage account $StorageAccountName does not exist; nothing to verify." }
$jobs = Update-Status (Get-Manifest)
$notDone = @($jobs | Where-Object { $_.status -notin $successStates })
if ($notDone) { Write-Warning "Not all jobs finished: $(($notDone | ForEach-Object { "$($_.table)=$($_.status)" }) -join ', '). Verifying the finished ones; do NOT run Hold yet." }
$finished = @($jobs | Where-Object { $_.jobId -and $_.status -in $successStates })
Write-Host "`n[1/3] Row counts, workspace vs export" -ForegroundColor Cyan
$rows = foreach ($j in $finished) {
$r = Invoke-Kql "$($j.table) | where TimeGenerated $kqlWindow | summarize Rows = count(), GB = round(sum(_BilledSize)/1024/1024/1024, 3)" | Select-Object -First 1
[pscustomobject]@{ Table = $j.table; WorkspaceRows = [long]$r.Rows; ExportedRows = [long]$j.resultCount; Match = ([long]$r.Rows -eq [long]$j.resultCount); WorkspaceGB = $r.GB; Status = $j.status }
}
$rows | Format-Table -AutoSize | Out-String -Width 200 | Write-Host
$rowPath = Join-Path $WorkDir 'rowcount-verification.csv'
$rows | Export-Csv $rowPath -NoTypeInformation
# A mismatch is not automatically a problem: the workspace count rises with late-arriving data and drops
# when retention purges the oldest part of the window. Explain any difference in the case file.
Write-Host '[2/3] SHA-256 of every blob (downloaded one at a time to temp, then deleted)' -ForegroundColor Cyan
$c = Get-StorageCtx
$tmp = Join-Path ([System.IO.Path]::GetTempPath()) 'la-export-blob'
$hashes = foreach ($j in $finished) {
foreach ($b in (Get-AzStorageBlob -Container $j.container -Context $c)) {
Get-AzStorageBlobContent -CloudBlob $b.ICloudBlob -Destination $tmp -Context $c -Force | Out-Null
$h = (Get-FileHash $tmp -Algorithm SHA256).Hash
Remove-Item $tmp -Force
[pscustomobject]@{ Table = $j.table; Container = $j.container; Blob = $b.Name; Bytes = $b.Length; ETag = $b.ICloudBlob.Properties.ETag; LastModifiedUtc = $b.LastModified.UtcDateTime.ToString('o'); Sha256 = $h }
}
Write-Host " $($j.table): hashed"
}
$hashPath = Join-Path $WorkDir 'blob-hashes.csv'
$hashes | Export-Csv $hashPath -NoTypeInformation
$totalGB = [math]::Round((($hashes | Measure-Object Bytes -Sum).Sum) / 1GB, 2)
Write-Host " $($hashes.Count) blobs, $totalGB GB in storage"
Write-Host "[3/3] Upload manifests to container 'evidence-manifest'" -ForegroundColor Cyan
$manifestHash = (Get-FileHash $hashPath -Algorithm SHA256).Hash
"$manifestHash blob-hashes.csv" | Set-Content (Join-Path $WorkDir 'blob-hashes.sha256')
New-AzStorageContainer -Name 'evidence-manifest' -Context $c -ErrorAction SilentlyContinue | Out-Null
foreach ($f in 'export-jobs.json', 'rowcount-verification.csv', 'blob-hashes.csv', 'blob-hashes.sha256') {
Set-AzStorageBlobContent -File (Join-Path $WorkDir $f) -Container 'evidence-manifest' -Blob $f -Context $c -Force | Out-Null
}
Write-Host "`nSHA-256 of blob-hashes.csv = $manifestHash (record this in the case file)" -ForegroundColor Green
Write-Host "Download the CSVs from Cloud Shell too before the session ends: $WorkDir"
}
'Hold' {
if (-not $existingSa) { throw "storage account $StorageAccountName does not exist; nothing to hold." }
$jobs = Update-Status (Get-Manifest)
$unfinished = @($jobs | Where-Object { $_.status -notin $successStates })
if ($unfinished) { throw "Refusing to apply the hold: $(($unfinished | ForEach-Object { "$($_.table)=$($_.status)" }) -join ', ') not finished. Retries need write access, so Hold comes last." }
$c = Get-StorageCtx
$containers = @($jobs | Where-Object jobId | ForEach-Object container) + 'evidence-manifest' | Select-Object -Unique
foreach ($name in $containers) {
if (Get-AzStorageContainer -Name $name -Context $c -ErrorAction SilentlyContinue) {
Add-AzRmStorageContainerLegalHold -ResourceGroupName $StorageResourceGroup -StorageAccountName $StorageAccountName -ContainerName $name -Tag $CaseTag | Out-Null
Write-Host " legal hold '$CaseTag' on $name" -ForegroundColor Green
}
}
Write-Host "`nLegal hold applied ('export-work' deliberately left out). Blobs in these containers cannot be modified or deleted until the hold is cleared." -ForegroundColor Green
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment