#Requires -Version 7.0 <# .SYNOPSIS READ-ONLY Azure inventory + relationship map + security / cost-hygiene findings, exported for dashboards. .DESCRIPTION Uses Azure Resource Graph (paged queries across all subscriptions at once) instead of looping Get-AzResource per subscription. READ-ONLY against Azure: it only runs Resource Graph queries (plus Get-AzRoleAssignment with -IncludeRbac). It never creates, modifies or deletes Azure resources. Local side effects only: may install Az modules for the current user, writes files to -OutputPath, and with -IncludeRbac switches the Az PowerShell context per subscription (restored at the end). Output (CSVs are UTF-8 with BOM so Excel opens them cleanly): subscriptions.csv subscriptions in scope resource_groups.csv resource groups + resource counts resources.csv every resource (flattened; VM size, power state, identity, tags) tags.csv one row per resource tag (resource_id, tag_key, tag_value) type_summary.csv resource count per subscription / type relationships.csv edges: source resource -> target resource (relation + JSON path) graph.json nodes (subscription / resourceGroup / resource / external) + edges findings_summary.csv one row per check: severity, count, status, recommendation findings_all.csv every finding in one long table (best source for dashboards) findings_.csv affected resources per check (only for checks with results) rbac_assignments.csv (-IncludeRbac) role assignments per subscription cost_by_resource.csv cost per resource and service: last month + month to date (skip with -SkipCost) cost_daily.csv daily cost per subscription and service for the last -CostDays days cost_status.csv per subscription: cost data status, currency and totals cost_monthly.csv monthly cost per subscription and service for the last -CostMonths months cost_by_meter.csv last month's cost per resource and meter (e.g. 'D4as v5', 'P10 LRS Disk') cost_by_pricing.csv last month's cost by pricing model (OnDemand, Reservation, SavingsPlan, Spot) and charge type resources_full.json (-IncludeProperties) raw properties of every resource run_metadata.json run time, tenant, account, counts .zip everything zipped .NOTES Requirements : PowerShell 7+, Az.Accounts, Az.ResourceGraph (Az.Resources for -IncludeRbac). Azure Cloud Shell (PowerShell) already has all of these. Permissions : Reader on the subscriptions. Security Reader for Defender for Cloud findings. Cost Management Reader (or Reader) for cost data. CSP subscriptions only return cost data when the partner has enabled cost visibility for the customer (shown at pay-as-you-go rates). Directory read in Entra ID for RBAC principal names (-IncludeRbac). Join key : resource ids are lower-cased in every output so they join directly to cost exports. .EXAMPLE ./Get-AzureInventory.ps1 .EXAMPLE ./Get-AzureInventory.ps1 -CostOnly # refresh cost data only, a few minutes .EXAMPLE ./Get-AzureInventory.ps1 -SubscriptionIds 'xxxxxxxx-...','yyyyyyyy-...' -IncludeRbac -IncludeProperties #> [CmdletBinding()] param( [string] $TenantId, [string[]]$SubscriptionIds, [string] $OutputPath = (Join-Path (Get-Location) ("AzureInventory_{0}" -f (Get-Date -Format 'yyyyMMdd_HHmm'))), [switch] $IncludeProperties, [switch] $IncludeRbac, [ValidateRange(1, 3650)] [int]$SnapshotAgeDays = 90, [ValidateRange(100, 1000)][int]$PageSize = 1000, [switch] $SkipCost, # Collect cost data only (fast). Load its zip in the dashboard together with the inventory zip. [switch] $CostOnly, [ValidateSet('AmortizedCost', 'ActualCost')][string]$CostType = 'AmortizedCost', [ValidateRange(7, 31)] [int]$CostDays = 30, [ValidateRange(2, 12)] [int]$CostMonths = 6 ) $ErrorActionPreference = 'Stop' $ScriptVersion = '2.3.0' $timer = [System.Diagnostics.Stopwatch]::StartNew() $CsvEncoding = 'utf8BOM' $script:ParseErrors = 0 # ============================================================ modules / login $required = @('Az.Accounts', 'Az.ResourceGraph') if ($IncludeRbac) { $required += 'Az.Resources' } foreach ($m in $required) { if (-not (Get-Module -ListAvailable -Name $m)) { Write-Host "Installing module $m (CurrentUser scope) ..." -ForegroundColor Yellow Install-Module $m -Scope CurrentUser -Repository PSGallery -Force } Import-Module $m } # Older Az.ResourceGraph versions have no -SkipToken and silently stop at the first page. if (-not (Get-Command Search-AzGraph).Parameters.ContainsKey('SkipToken')) { throw 'Az.ResourceGraph is too old (no -SkipToken paging). Run: Update-Module Az.ResourceGraph' } $ctx = Get-AzContext if (-not $ctx -or ($TenantId -and $ctx.Tenant.Id -ne $TenantId)) { $connect = @{} if ($TenantId) { $connect.TenantId = $TenantId } Connect-AzAccount @connect | Out-Null $ctx = Get-AzContext } $TenantId = $ctx.Tenant.Id $originalContext = $ctx $OutputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath) if ($CostOnly -and -not $PSBoundParameters.ContainsKey('OutputPath')) { $OutputPath = Join-Path (Get-Location) ("AzureCost_{0}" -f (Get-Date -Format 'yyyyMMdd_HHmm')) } if ($CostOnly -and $SkipCost) { throw '-CostOnly and -SkipCost cannot be used together.' } New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null function Save-Csv { param([Parameter(Mandatory)][string]$Name, [object[]]$Data) $Data = @($Data | Where-Object { $null -ne $_ }) if ($Data.Count) { $Data | Export-Csv -Path (Join-Path $OutputPath $Name) -NoTypeInformation -Encoding $CsvEncoding } } function ConvertFrom-JsonSafe { # -AsHashtable copes with keys that differ only by case (plain ConvertFrom-Json throws on those). param([string]$Json) if ([string]::IsNullOrWhiteSpace($Json) -or $Json -eq 'null') { return $null } try { return ($Json | ConvertFrom-Json -AsHashtable) } catch { $script:ParseErrors++; return $null } } # ============================================================ subscriptions (current tenant only) # Resource Graph only queries the tenant of the current context, so subscriptions from other # tenants are excluded (the original script mixed them in). $subs = @(Get-AzSubscription -TenantId $TenantId -WarningAction SilentlyContinue | Where-Object { $_.State -in 'Enabled', 'Warned', 'PastDue' } | Sort-Object Id -Unique) if ($SubscriptionIds) { $missing = @($SubscriptionIds | Where-Object { $_ -notin $subs.Id }) if ($missing) { Write-Warning ("Not found / not active in tenant {0}: {1}" -f $TenantId, ($missing -join ', ')) } $subs = @($subs | Where-Object { $_.Id -in $SubscriptionIds }) } if (-not $subs) { throw "No active subscriptions found / matched in tenant $TenantId." } $script:SubIds = @($subs.Id) $script:SubName = @{} foreach ($s in $subs) { $script:SubName[$s.Id] = $s.Name } Write-Host ("Tenant {0} | subscriptions in scope: {1}" -f $TenantId, $subs.Count) -ForegroundColor Cyan Save-Csv 'subscriptions.csv' ($subs | Select-Object @{n='subscription_id';e={$_.Id}}, @{n='subscription_name';e={$_.Name}}, @{n='tenant_id';e={$_.TenantId}}, @{n='state';e={$_.State}}) if (-not $CostOnly) { # ---------- inventory, relationships and findings (skipped with -CostOnly) # ============================================================ Resource Graph helper (paged + retry) # Every query must project an 'id' column, otherwise Resource Graph paging does not work. function Invoke-Graph { param([Parameter(Mandatory)][string]$Query) $out = [System.Collections.Generic.List[object]]::new() $skip = $null do { $p = @{ Query = $Query; First = $PageSize; Subscription = $script:SubIds } if ($skip) { $p.SkipToken = $skip } $attempt = 0 while ($true) { try { $resp = Search-AzGraph @p; break } catch { $attempt++ $msg = $_.Exception.Message if ($attempt -ge 6 -or $msg -notmatch '429|RateLimit|throttl|timed? ?out|temporar|503|502') { throw } $wait = [math]::Min(60, 5 * [math]::Pow(2, $attempt - 1)) Write-Warning ("Resource Graph throttled / transient error. Retry {0}/5 in {1}s" -f $attempt, $wait) Start-Sleep -Seconds $wait } } foreach ($row in @($resp.Data)) { if ($null -ne $row) { $out.Add($row) } } $skip = $resp.SkipToken } while ($skip) # Rows are written to the pipeline; callers wrap the call in @() to always get an array. # (v2.0.0 used 'return ,' together with @(), which nested the array and broke every Resource Graph check.) $out.ToArray() } # ============================================================ resource groups + resources Write-Host 'Collecting resource groups ...' -ForegroundColor Cyan $rgs = @(Invoke-Graph @' resourcecontainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | project id, name, subscriptionId, location, tagsJson = tostring(tags) '@) Write-Host 'Collecting resources ...' -ForegroundColor Cyan $resources = @(Invoke-Graph @' resources | project id, name, type, kind, location, subscriptionId, resourceGroup, managedBy, zones = tostring(zones), skuJson = tostring(sku), tagsJson = tostring(tags), identityJson = tostring(identity), vmSize = tostring(properties.hardwareProfile.vmSize), powerState = tostring(properties.extended.instanceView.powerState.code), osType = coalesce(tostring(properties.storageProfile.osDisk.osType), tostring(properties.osType)), provisioningState = tostring(properties.provisioningState), timeCreated = tostring(properties.timeCreated), propsJson = tostring(properties) '@) Write-Host (" {0} resources found" -f $resources.Count) -ForegroundColor Green $idx = @{} # lower-case id -> resource foreach ($r in $resources) { $idx[$r.id.ToLower()] = $r } # ============================================================ relationship helpers $IdPattern = '^/subscriptions/[0-9a-fA-F\-]{36}/resourceGroups/[^/]+/providers/.+' function Resolve-TargetId { # Walks up child ids (e.g. .../virtualNetworks/v/subnets/s -> .../virtualNetworks/v) until a known resource. param([string]$Id) $c = $Id.TrimEnd('/').ToLower() while ($true) { if ($idx.ContainsKey($c)) { return $c } $parts = $c.Split('/') if ($parts.Length -le 9) { return $null } # /subscriptions/x/resourcegroups/y/providers/ns/type/name $c = ($parts[0..($parts.Length - 3)] -join '/') } } function Get-IdRefs { # Recursively finds resource-id strings in parsed JSON and records the full JSON path to each. param($Node, [string]$Path, [int]$Depth, $Acc) if ($null -eq $Node -or $Depth -gt 20) { return } if ($Node -is [string]) { if ($Node -match $IdPattern) { $Acc.Add([pscustomobject]@{ Path = $Path; Id = $Node }) } return } if ($Node -is [System.Collections.IDictionary]) { foreach ($k in @($Node.Keys)) { if ($k -is [string] -and $k -match $IdPattern) { # resource ids used as keys, e.g. identity.userAssignedIdentities $Acc.Add([pscustomobject]@{ Path = $Path; Id = $k }) Get-IdRefs -Node $Node[$k] -Path "$Path." -Depth ($Depth + 1) -Acc $Acc } else { Get-IdRefs -Node $Node[$k] -Path "$Path.$k" -Depth ($Depth + 1) -Acc $Acc } } return } if ($Node -is [System.Collections.IEnumerable]) { foreach ($i in $Node) { Get-IdRefs -Node $i -Path "$Path[]" -Depth ($Depth + 1) -Acc $Acc } } } function Get-RelationName { # 'properties.ipConfigurations[].properties.subnet.id' -> 'subnet' param([string]$Path) $segs = @(($Path -replace '\[\]', '') -split '\.' | Where-Object { $_ -and $_ -notin 'properties', 'id', '', 'resourceId' }) if ($segs.Count) { return $segs[-1] } else { return 'reference' } } function Split-ResourceId { param([string]$Id) $m = [regex]::Match([string]$Id, '(?i)^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/(.+)$') if (-not $m.Success) { return @{ Sub = $null; Rg = $null; Type = $null; Name = $Id } } $segs = $m.Groups[3].Value.Split('/') $type = $segs[0] for ($i = 1; $i -lt $segs.Length - 1; $i += 2) { $type += '/' + $segs[$i] } return @{ Sub = $m.Groups[1].Value; Rg = $m.Groups[2].Value; Type = $type; Name = $segs[-1] } } $edges = [System.Collections.Generic.List[object]]::new() $seen = @{} function Add-Edge { param([string]$SrcKey, [string]$RawTarget, [string]$Relation, [string]$RelationPath) $src = $idx[$SrcKey] $t = Resolve-TargetId $RawTarget if ($t) { $tid = $t; $tr = $idx[$t]; $inInv = $true $tName = $tr.name; $tType = $tr.type; $tSub = $tr.subscriptionId; $tRg = $tr.resourceGroup } else { $tid = $RawTarget.TrimEnd('/').ToLower(); $inInv = $false $pi = Split-ResourceId $RawTarget $tName = $pi.Name; $tType = $pi.Type; $tSub = $pi.Sub; $tRg = $pi.Rg } if ($tid -eq $SrcKey) { return } # self reference (e.g. own ipConfigurations) $key = "$SrcKey|$tid|$Relation" if ($seen.ContainsKey($key)) { return } $seen[$key] = 1 $edges.Add([pscustomobject]@{ source_id = $SrcKey source_name = $src.name source_type = $src.type source_subscription = $script:SubName[[string]$src.subscriptionId] source_rg = $src.resourceGroup relation = $Relation relation_path = $RelationPath target_id = $tid target_name = $tName target_type = $tType target_subscription = if ($tSub) { $script:SubName[[string]$tSub] } else { $null } target_subscription_id = $tSub target_rg = $tRg target_detail = $RawTarget target_in_inventory = $inInv cross_subscription = [bool]($tSub -and $tSub -ne $src.subscriptionId) cross_resource_group = [bool]($tRg -and $tRg -ne $src.resourceGroup) }) } # ============================================================ single pass: flat table, tags, relationships Write-Host 'Flattening resources and building relationships ...' -ForegroundColor Cyan $resFlat = [System.Collections.Generic.List[object]]::new() $tagRows = [System.Collections.Generic.List[object]]::new() $rgCounts = @{} $n = 0 foreach ($r in $resources) { $n++ if ($n % 1000 -eq 0) { Write-Host (" processed {0}/{1}" -f $n, $resources.Count) } $key = $r.id.ToLower() $sku = ConvertFrom-JsonSafe $r.skuJson $tags = ConvertFrom-JsonSafe $r.tagsJson $ident = ConvertFrom-JsonSafe $r.identityJson $identityType = if ($ident -is [System.Collections.IDictionary] -and $ident['type']) { [string]$ident['type'] } else { 'None' } $tagCount = if ($tags -is [System.Collections.IDictionary]) { $tags.Count } else { 0 } $subNm = $script:SubName[[string]$r.subscriptionId] $resFlat.Add([pscustomobject]@{ subscription_id = $r.subscriptionId subscription_name = $subNm resource_group = $r.resourceGroup name = $r.name type = $r.type kind = $r.kind location = $r.location sku_name = if ($sku -is [System.Collections.IDictionary]) { $sku['name'] } else { $null } sku_tier = if ($sku -is [System.Collections.IDictionary]) { $sku['tier'] } else { $null } vm_size = $r.vmSize power_state = ($r.powerState -replace '^PowerState/', '') os_type = $r.osType provisioning_state = $r.provisioningState time_created = $r.timeCreated zones = $r.zones identity_type = $identityType has_identity = ($identityType -ne 'None') tag_count = $tagCount tags = $r.tagsJson managed_by = $r.managedBy id = $key }) if ($tagCount) { foreach ($tk in $tags.Keys) { $tagRows.Add([pscustomobject]@{ resource_id = $key; subscription_name = $subNm; resource_group = $r.resourceGroup name = $r.name; type = $r.type; tag_key = $tk; tag_value = [string]$tags[$tk] }) } } $rgKey = ("{0}|{1}" -f $r.subscriptionId, $r.resourceGroup).ToLower() $rgCounts[$rgKey] = 1 + [int]$rgCounts[$rgKey] # --- relationships $refs = [System.Collections.Generic.List[object]]::new() $props = ConvertFrom-JsonSafe $r.propsJson if ($props) { Get-IdRefs -Node $props -Path 'properties' -Depth 0 -Acc $refs } if ($ident) { Get-IdRefs -Node $ident -Path 'identity' -Depth 0 -Acc $refs } if ($r.managedBy) { $refs.Add([pscustomobject]@{ Path = 'managedBy'; Id = $r.managedBy }) } foreach ($ref in $refs) { Add-Edge -SrcKey $key -RawTarget $ref.Id -Relation (Get-RelationName $ref.Path) -RelationPath $ref.Path } # structural parent, e.g. SQL database -> SQL server (child id = 11 segments; original used -gt 11 and missed these) $parts = $key.Split('/') if ($parts.Length -ge 11) { $parent = ($parts[0..($parts.Length - 3)] -join '/') if ($idx.ContainsKey($parent)) { Add-Edge -SrcKey $key -RawTarget $parent -Relation 'parent' -RelationPath 'id' } } } Write-Host (" {0} relationships found" -f $edges.Count) -ForegroundColor Green Save-Csv 'resources.csv' $resFlat Save-Csv 'tags.csv' $tagRows Save-Csv 'relationships.csv' $edges $rgFlat = foreach ($g in $rgs) { [pscustomobject]@{ subscription_id = $g.subscriptionId subscription_name = $script:SubName[[string]$g.subscriptionId] resource_group = $g.name location = $g.location resource_count = [int]$rgCounts[("{0}|{1}" -f $g.subscriptionId, $g.name).ToLower()] tags = $g.tagsJson id = $g.id.ToLower() } } Save-Csv 'resource_groups.csv' $rgFlat Save-Csv 'type_summary.csv' ($resFlat | Group-Object subscription_name, type | ForEach-Object { [pscustomobject]@{ subscription_name = $_.Group[0].subscription_name; type = $_.Group[0].type; count = $_.Count } } | Sort-Object subscription_name, @{e = 'count'; Descending = $true }) # ============================================================ graph.json (hierarchy + relationships) $nodes = [System.Collections.Generic.List[object]]::new() foreach ($s in $subs) { $nodes.Add([pscustomobject]@{ id = "/subscriptions/$($s.Id)".ToLower(); name = $s.Name; kind = 'subscription'; parent = $null }) } foreach ($g in $rgFlat) { $nodes.Add([pscustomobject]@{ id = $g.id; name = $g.resource_group; kind = 'resourceGroup' parent = "/subscriptions/$($g.subscription_id)".ToLower(); location = $g.location; resourceCount = $g.resource_count }) } foreach ($f in $resFlat) { $nodes.Add([pscustomobject]@{ id = $f.id; name = $f.name; kind = 'resource'; type = $f.type; location = $f.location subscription = $f.subscription_name; resourceGroup = $f.resource_group parent = ("/subscriptions/{0}/resourcegroups/{1}" -f $f.subscription_id, $f.resource_group).ToLower() }) } $extSeen = @{} foreach ($e in $edges | Where-Object { -not $_.target_in_inventory }) { if ($extSeen.ContainsKey($e.target_id)) { continue } $extSeen[$e.target_id] = 1 $nodes.Add([pscustomobject]@{ id = $e.target_id; name = $e.target_name; kind = 'external'; type = $e.target_type; parent = $null }) } $graph = [ordered]@{ generatedUtc = (Get-Date).ToUniversalTime().ToString('o') nodes = $nodes edges = @($edges | ForEach-Object { [pscustomobject]@{ source = $_.source_id; target = $_.target_id; relation = $_.relation } }) } $graph | ConvertTo-Json -Depth 6 -Compress | Set-Content (Join-Path $OutputPath 'graph.json') -Encoding utf8NoBOM # ============================================================ optional raw properties (streamed, lossless) if ($IncludeProperties) { Write-Host 'Writing resources_full.json ...' -ForegroundColor Cyan $writer = [System.IO.StreamWriter]::new((Join-Path $OutputPath 'resources_full.json'), $false, [System.Text.UTF8Encoding]::new($false)) try { $writer.Write('[') $first = $true foreach ($r in $resources) { if (-not $first) { $writer.Write(',') } $first = $false $meta = [ordered]@{ id = $r.id.ToLower(); name = $r.name; type = $r.type; subscriptionId = $r.subscriptionId resourceGroup = $r.resourceGroup; location = $r.location } | ConvertTo-Json -Compress $raw = if ([string]::IsNullOrWhiteSpace($r.propsJson)) { 'null' } else { $r.propsJson } $writer.Write($meta.Substring(0, $meta.Length - 1) + ',"properties":' + $raw + '}') } $writer.Write(']') } finally { $writer.Dispose() } } # ============================================================ findings framework $summary = [System.Collections.Generic.List[object]]::new() $allFindings = [System.Collections.Generic.List[object]]::new() function Register-Finding { param([string]$Check, [string]$Severity, [string]$Advice, [object[]]$Rows, [string]$Status = 'OK') $Rows = @($Rows | Where-Object { $null -ne $_ }) if ($Rows.Count) { $withSub = @($Rows | Select-Object *, @{ n = 'subscriptionName'; e = { $script:SubName[[string]$_.subscriptionId] } }) Save-Csv "findings_$Check.csv" $withSub foreach ($row in $withSub) { $p = $row.PSObject.Properties $rid = if ($p['resourceId'] -and $row.resourceId) { [string]$row.resourceId } else { [string]$row.id } $pi = Split-ResourceId $rid $name = if ($p['resourceName'] -and $row.resourceName) { $row.resourceName } elseif ($p['name'] -and $row.name) { $row.name } else { $pi.Name } $rg = if ($p['resourceGroup'] -and $row.resourceGroup) { $row.resourceGroup } else { $pi.Rg } $sev = if ($p['severity'] -and $row.severity) { $row.severity } else { $Severity } $loc = if ($p['location']) { $row.location } else { $null } $det = $row | Select-Object * -ExcludeProperty id, name, resourceId, resourceName, resourceGroup, subscriptionId, subscriptionName, location, severity | ConvertTo-Json -Compress -Depth 4 $allFindings.Add([pscustomobject]@{ check = $Check; severity = $sev; resource_id = $rid.ToLower(); resource_name = $name resource_group = $rg; subscription_name = $row.subscriptionName; location = $loc details = $det; recommendation = $Advice }) } } $summary.Add([pscustomobject]@{ check = $Check; severity = $Severity; count = $Rows.Count; status = $Status; recommendation = $Advice }) Write-Host (" {0,-40} {1}" -f $Check, $Rows.Count) } # ============================================================ Resource Graph checks Write-Host 'Running security / cost / hygiene checks ...' -ForegroundColor Cyan $checks = [ordered]@{ # ---------------- cost / hygiene 'orphaned_disks' = @{ Severity = 'Medium' Advice = 'Unattached managed disks are billed and may hold data. ASR replica/seed disks are excluded (deleting them breaks DR). Snapshot if needed, then delete.' Query = @' resources | where type =~ 'microsoft.compute/disks' | extend diskState = tostring(properties.diskState) | where isempty(managedBy) and diskState =~ 'Unattached' | where not(name endswith '-ASRReplica' or name startswith 'ms-asr-' or name startswith 'asrseeddisk-') | project id, name, resourceGroup, subscriptionId, location, diskState, sizeGB = toint(properties.diskSizeGB), sku = tostring(sku.name), timeCreated = tostring(properties.timeCreated) '@ } 'unassociated_public_ips' = @{ Severity = 'Medium' Advice = 'Public IPs not attached to any NIC, LB, gateway, firewall, Bastion or NAT gateway. Static IPs are billed; delete if unused (check DNS / whitelists first).' Query = @' resources | where type =~ 'microsoft.network/publicipaddresses' | where isempty(tostring(properties.ipConfiguration)) and isempty(tostring(properties.natGateway)) | project id, name, resourceGroup, subscriptionId, location, sku = tostring(sku.name), allocation = tostring(properties.publicIPAllocationMethod), ipAddress = tostring(properties.ipAddress) '@ } 'orphaned_nics' = @{ Severity = 'Low' Advice = 'NICs attached to no VM, private endpoint, private link service or hosted workload. Delete after verification.' Query = @' resources | where type =~ 'microsoft.network/networkinterfaces' | where isnull(properties.virtualMachine) and isnull(properties.privateEndpoint) and isnull(properties.privateLinkService) | where isnull(properties.hostedWorkloads) or array_length(properties.hostedWorkloads) == 0 | project id, name, resourceGroup, subscriptionId, location '@ } 'unattached_nsgs' = @{ Severity = 'Low' Advice = 'NSGs not associated with any subnet or NIC. Remove, or attach where intended.' Query = @' resources | where type =~ 'microsoft.network/networksecuritygroups' | where coalesce(array_length(properties.networkInterfaces), 0) == 0 and coalesce(array_length(properties.subnets), 0) == 0 | project id, name, resourceGroup, subscriptionId, location '@ } 'vm_stopped_not_deallocated' = @{ Severity = 'High' Advice = 'VM is Stopped from inside the OS but NOT deallocated: compute is still billed. Stop (deallocate) from Portal/automation if not needed.' Query = @' resources | where type =~ 'microsoft.compute/virtualmachines' | extend powerState = tostring(properties.extended.instanceView.powerState.code) | where powerState =~ 'PowerState/stopped' | project id, name, resourceGroup, subscriptionId, location, vmSize = tostring(properties.hardwareProfile.vmSize), powerState '@ } 'vm_deallocated' = @{ Severity = 'Info' Advice = 'Deallocated VMs: no compute cost, but disks / static IPs are still billed. Ignore VMs on scheduled start/stop; review long-idle ones.' Query = @' resources | where type =~ 'microsoft.compute/virtualmachines' | extend powerState = tostring(properties.extended.instanceView.powerState.code) | where powerState =~ 'PowerState/deallocated' | project id, name, resourceGroup, subscriptionId, location, vmSize = tostring(properties.hardwareProfile.vmSize), powerState '@ } 'old_snapshots' = @{ Severity = 'Low' Advice = "Disk snapshots older than $SnapshotAgeDays days. Check whether still required (retention / rollback), then delete." Query = (@' resources | where type =~ 'microsoft.compute/snapshots' | extend created = todatetime(properties.timeCreated) | where created < ago(__DAYS__d) | project id, name, resourceGroup, subscriptionId, location, timeCreated = tostring(created), sizeGB = toint(properties.diskSizeGB), sku = tostring(sku.name), incremental = tostring(properties.incremental), sourceResourceId = tostring(properties.creationData.sourceResourceId) '@).Replace('__DAYS__', [string]$SnapshotAgeDays) } 'empty_app_service_plans' = @{ Severity = 'Medium' Advice = 'App Service plans hosting no apps are still billed (except Free tier). Delete or consolidate.' Query = @' resources | where type =~ 'microsoft.web/serverfarms' | where toint(properties.numberOfSites) == 0 | project id, name, resourceGroup, subscriptionId, location, sku = tostring(sku.name), tier = tostring(sku.tier) '@ } 'lb_without_backend_pools' = @{ Severity = 'Low' Advice = 'Load balancers with no backend pools. Standard LB is billed per rule; delete if unused.' Query = @' resources | where type =~ 'microsoft.network/loadbalancers' | where coalesce(array_length(properties.backendAddressPools), 0) == 0 | project id, name, resourceGroup, subscriptionId, location, sku = tostring(sku.name) '@ } 'basic_sku_network' = @{ Severity = 'High' Advice = 'Basic SKU Public IPs / Load Balancers are retired by Microsoft. Upgrade to Standard SKU (plan NSG + downtime; follow the official upgrade guidance).' Query = @' resources | where type in~ ('microsoft.network/publicipaddresses', 'microsoft.network/loadbalancers') | where tostring(sku.name) =~ 'Basic' | project id, name, type, resourceGroup, subscriptionId, location, sku = tostring(sku.name) '@ } 'untagged_resources' = @{ Severity = 'Low' Advice = 'Resources with no tags. Add owner / environment / cost-center / application tags for governance and cost allocation.' Query = @' resources | where isnull(tags) or tostring(tags) in ('{}', '') | project id, name, type, resourceGroup, subscriptionId, location '@ } # ---------------- security 'nsg_inbound_from_internet' = @{ Severity = 'High' Advice = 'Inbound Allow rules from any / Internet. Critical = all ports or mgmt/DB ports (22, 3389, 1433, 445 ...). Restrict source IPs; use Bastion / JIT for RDP and SSH.' Query = @' resources | where type =~ 'microsoft.network/networksecuritygroups' | mv-expand rule = properties.securityRules | extend direction = tostring(rule.properties.direction), access = tostring(rule.properties.access), src = tostring(rule.properties.sourceAddressPrefix), srcs = tostring(rule.properties.sourceAddressPrefixes) | where direction =~ 'Inbound' and access =~ 'Allow' | where src in~ ('*', '0.0.0.0/0', 'Internet', 'Any') or srcs contains '"*"' or srcs contains '0.0.0.0/0' or srcs contains '"Internet"' | project id, name, resourceGroup, subscriptionId, location, ruleName = tostring(rule.name), priority = toint(rule.properties.priority), protocol = tostring(rule.properties.protocol), destinationPort = tostring(rule.properties.destinationPortRange), destinationPorts = tostring(rule.properties.destinationPortRanges), source = iff(isempty(src), srcs, src) '@ Post = { param($rows) $risky = 21, 22, 23, 135, 139, 445, 1433, 1434, 3306, 3389, 5432, 5985, 5986, 6379, 9200, 27017 foreach ($row in $rows) { $tokens = [System.Collections.Generic.List[string]]::new() if ($row.destinationPort) { $tokens.Add([string]$row.destinationPort) } if (([string]$row.destinationPorts).StartsWith('[')) { foreach ($t in ([string]$row.destinationPorts | ConvertFrom-Json)) { if ($t) { $tokens.Add([string]$t) } } } $all = $false; $hit = [System.Collections.Generic.List[int]]::new(); $webOnly = $tokens.Count -gt 0 foreach ($t in $tokens) { if ($t -notin '80', '443') { $webOnly = $false } if ($t -eq '*') { $all = $true } elseif ($t -match '^(\d+)-(\d+)$') { $lo = [int]$Matches[1]; $hi = [int]$Matches[2] foreach ($rp in $risky) { if ($rp -ge $lo -and $rp -le $hi) { $hit.Add($rp) } } } elseif ($t -match '^\d+$' -and [int]$t -in $risky) { $hit.Add([int]$t) } } $sev = if ($all -or $hit.Count) { 'Critical' } elseif ($webOnly) { 'Medium' } else { 'High' } $rp = if ($all) { 'ALL' } else { ($hit | Sort-Object -Unique) -join ',' } $row | Add-Member -NotePropertyName severity -NotePropertyValue $sev -Force $row | Add-Member -NotePropertyName riskyPorts -NotePropertyValue $rp -Force } $rows } } 'nics_with_public_ip' = @{ Severity = 'Medium' Advice = 'NICs (usually VMs) with a directly attached public IP. Prefer Bastion / LB / App Gateway / NAT gateway, and make sure NSGs restrict sources.' Query = @' resources | where type =~ 'microsoft.network/networkinterfaces' | mv-expand ipc = properties.ipConfigurations | where isnotempty(tostring(ipc.properties.publicIPAddress.id)) | project id, name, resourceGroup, subscriptionId, location, ipConfig = tostring(ipc.name), publicIpId = tostring(ipc.properties.publicIPAddress.id), vmId = tostring(properties.virtualMachine.id) '@ } 'storage_weak_settings' = @{ Severity = 'High' Advice = 'Storage accounts allowing anonymous blob access, HTTP, TLS < 1.2 or all networks. See the reasons column; harden and prefer private endpoints.' Query = @' resources | where type =~ 'microsoft.storage/storageaccounts' | extend allowBlobPublicAccess = tostring(properties.allowBlobPublicAccess), httpsOnly = tostring(properties.supportsHttpsTrafficOnly), minTls = tostring(properties.minimumTlsVersion), publicNetworkAccess = tostring(properties.publicNetworkAccess), firewallDefault = tostring(properties.networkAcls.defaultAction) | where allowBlobPublicAccess !~ 'false' or httpsOnly =~ 'false' or minTls in~ ('TLS1_0', 'TLS1_1', '') or (firewallDefault =~ 'Allow' and publicNetworkAccess !~ 'Disabled') | project id, name, resourceGroup, subscriptionId, location, allowBlobPublicAccess, httpsOnly, minTls, publicNetworkAccess, firewallDefault '@ Post = { param($rows) foreach ($row in $rows) { $why = @() if ([string]$row.allowBlobPublicAccess -ne 'false') { $why += 'BlobAnonymousAccessAllowed' } if ([string]$row.httpsOnly -eq 'false') { $why += 'HttpAllowed' } if ([string]::IsNullOrEmpty($row.minTls) -or $row.minTls -in 'TLS1_0', 'TLS1_1') { $why += 'MinTlsBelow1.2' } if ([string]$row.firewallDefault -eq 'Allow' -and [string]$row.publicNetworkAccess -ne 'Disabled') { $why += 'OpenToAllNetworks' } $sev = if ($why -contains 'BlobAnonymousAccessAllowed' -or $why -contains 'HttpAllowed') { 'High' } else { 'Medium' } $row | Add-Member -NotePropertyName reasons -NotePropertyValue ($why -join ';') -Force $row | Add-Member -NotePropertyName severity -NotePropertyValue $sev -Force } $rows } } 'sql_public_access' = @{ Severity = 'High' Advice = 'Azure SQL servers with public network access enabled or minimum TLS below 1.2. Prefer private endpoints; review server firewall rules; enforce TLS 1.2.' Query = @' resources | where type =~ 'microsoft.sql/servers' | extend publicNetworkAccess = tostring(properties.publicNetworkAccess), minimalTlsVersion = tostring(properties.minimalTlsVersion) | where publicNetworkAccess !~ 'Disabled' or minimalTlsVersion !in ('1.2', '1.3') | project id, name, resourceGroup, subscriptionId, location, publicNetworkAccess, minimalTlsVersion '@ } 'sqlmi_public_endpoint' = @{ Severity = 'High' Advice = 'SQL Managed Instances with the public data endpoint enabled. Disable unless explicitly required and restricted by NSG.' Query = @' resources | where type =~ 'microsoft.sql/managedinstances' | where tostring(properties.publicDataEndpointEnabled) =~ 'true' | project id, name, resourceGroup, subscriptionId, location '@ } 'keyvault_weak_settings' = @{ Severity = 'Medium' Advice = 'Key Vaults without purge protection, or reachable from all networks. Enable purge protection; set firewall to deny / use private endpoints; prefer RBAC model.' Query = @' resources | where type =~ 'microsoft.keyvault/vaults' | extend purgeProtection = tostring(properties.enablePurgeProtection), publicNetworkAccess = tostring(properties.publicNetworkAccess), firewallDefault = tostring(properties.networkAcls.defaultAction), rbac = tostring(properties.enableRbacAuthorization) | where purgeProtection !~ 'true' or (publicNetworkAccess !~ 'Disabled' and firewallDefault !~ 'Deny') | project id, name, resourceGroup, subscriptionId, location, purgeProtection, publicNetworkAccess, firewallDefault, rbac '@ } 'appservice_https_not_enforced' = @{ Severity = 'Medium' Advice = 'Web / Function apps that accept plain HTTP. Enable HTTPS Only.' Query = @' resources | where type =~ 'microsoft.web/sites' | where tostring(properties.httpsOnly) !~ 'true' | project id, name, kind, resourceGroup, subscriptionId, location, httpsOnly = tostring(properties.httpsOnly) '@ } 'advisor_cost_recommendations' = @{ Severity = 'Medium' Advice = 'Azure Advisor cost recommendations (rightsize or shut down VMs, reservations, savings plans). Savings are Advisor estimates; check usage before acting.' Query = @' advisorresources | where type =~ 'microsoft.advisor/recommendations' | where tostring(properties.category) =~ 'Cost' | extend ep = properties.extendedProperties | project id, subscriptionId, resourceGroup, resourceId = tolower(tostring(properties.resourceMetadata.resourceId)), resourceName = tostring(properties.impactedValue), impactedType = tostring(properties.impactedField), recommendation = tostring(properties.shortDescription.solution), impact = tostring(properties.impact), monthlySavings = todouble(ep.savingsAmount), annualSavings = todouble(ep.annualSavingsAmount), savingsCurrency = tostring(ep.savingsCurrency), currentSku = tostring(ep.currentSku), targetSku = tostring(ep.targetSku), term = tostring(ep.term), lookbackDays = tostring(ep.lookbackPeriod) '@ Post = { param($rows) foreach ($row in $rows) { $sev = switch ([string]$row.impact) { 'High' { 'High' } 'Medium' { 'Medium' } default { 'Low' } } $row | Add-Member -NotePropertyName severity -NotePropertyValue $sev -Force if (-not $row.monthlySavings -and $row.annualSavings) { $row.monthlySavings = [math]::Round([double]$row.annualSavings / 12, 2) } } $rows } } 'defender_unhealthy_recommendations' = @{ Severity = 'Varies' Advice = 'Open Defender for Cloud recommendations (needs Security Reader). Severity comes from Defender.' Query = @' securityresources | where type =~ 'microsoft.security/assessments' | where tostring(properties.status.code) =~ 'Unhealthy' | project id, subscriptionId, recommendation = tostring(properties.displayName), severity = tostring(properties.metadata.severity), resourceId = tostring(properties.resourceDetails.Id), resourceName = tostring(properties.resourceDetails.ResourceName) '@ } } foreach ($k in $checks.Keys) { $c = $checks[$k] try { $rows = @(Invoke-Graph -Query $c.Query) if ($c.Post -and $rows.Count) { $rows = @(& $c.Post $rows) } Register-Finding -Check $k -Severity $c.Severity -Advice $c.Advice -Rows $rows } catch { Write-Warning "Check '$k' failed: $($_.Exception.Message)" $summary.Add([pscustomobject]@{ check = $k; severity = $c.Severity; count = $null; status = "FAILED: $($_.Exception.Message)"; recommendation = $c.Advice }) } } # ============================================================ locally computed checks # Empty resource groups (no extra query needed) Register-Finding -Check 'empty_resource_groups' -Severity 'Low' ` -Advice 'Resource groups with no resources indexed by Resource Graph. Verify in the Portal (some hidden/child types are not indexed), then delete if not needed.' ` -Rows @($rgFlat | Where-Object { $_.resource_count -eq 0 } | ForEach-Object { [pscustomobject]@{ id = $_.id; name = $_.resource_group; resourceGroup = $_.resource_group; subscriptionId = $_.subscription_id; location = $_.location } }) # VMs without Azure Backup try { $protected = @(Invoke-Graph @' recoveryservicesresources | where type =~ 'microsoft.recoveryservices/vaults/backupfabrics/protectioncontainers/protecteditems' | extend sourceId = tolower(coalesce(tostring(properties.sourceResourceId), tostring(properties.dataSourceInfo.resourceID))) | where isnotempty(sourceId) | project id, sourceId, protectionState = tostring(properties.protectionState) '@) Write-Host (" Azure Backup protected items visible: {0}" -f $protected.Count) $prot = @{} foreach ($p in $protected) { $prot[$p.sourceId] = $p.protectionState } $vmRows = foreach ($v in $resFlat | Where-Object { $_.type -eq 'microsoft.compute/virtualmachines' }) { $state = $prot[$v.id] if (-not $state -or $state -eq 'ProtectionStopped') { [pscustomobject]@{ id = $v.id; name = $v.name; resourceGroup = $v.resource_group; subscriptionId = $v.subscription_id location = $v.location; backupState = if ($state) { $state } else { 'NotProtected' } } } } $backupStatus = if ($protected.Count -eq 0) { 'WARNING: no Azure Backup protected items were visible. Either nothing uses Azure Backup, or this account cannot read the Recovery Services vaults - verify before acting.' } else { 'OK' } Register-Finding -Check 'vms_without_backup' -Severity 'High' -Status $backupStatus ` -Advice ("VMs with no Azure Backup protected item (or protection stopped). {0} protected items were visible. ASR replication is DR, not backup. Verify other backup tooling before acting." -f $protected.Count) -Rows @($vmRows) } catch { Write-Warning "Check 'vms_without_backup' failed: $($_.Exception.Message)" $summary.Add([pscustomobject]@{ check = 'vms_without_backup'; severity = 'High'; count = $null; status = "FAILED: $($_.Exception.Message)"; recommendation = '' }) } # References to resources that do not exist in scope (stale references or non-indexed types) # creationData / source* paths are history (e.g. the snapshot a disk was built from), not live configuration. $dangling = $edges | Where-Object { -not $_.target_in_inventory -and $_.target_subscription_id -and ($script:SubIds -contains $_.target_subscription_id) -and $_.relation_path -notmatch '(?i)creationData|sourceResourceId|sourceVirtualMachine|\.source\b' } | Group-Object target_id | ForEach-Object { $e = $_.Group[0] [pscustomobject]@{ id = $e.target_id; name = $e.target_name; type = $e.target_type; resourceGroup = $e.target_rg subscriptionId = $e.target_subscription_id; referencedBy = (($_.Group.source_name | Sort-Object -Unique) -join ';') referenceCount = $_.Count; relationPaths = (($_.Group.relation_path | Sort-Object -Unique) -join ';') } } Register-Finding -Check 'references_to_missing_resources' -Severity 'Info' ` -Advice 'Resources referencing an id that Resource Graph cannot find in scope: possibly deleted (stale config) or a type Resource Graph does not index. Verify before acting.' -Rows @($dangling) # ============================================================ optional RBAC if ($IncludeRbac) { Write-Host 'Collecting RBAC role assignments (slower) ...' -ForegroundColor Cyan function Get-ScopeLevel([string]$Scope) { switch -Regex ($Scope) { '^/$' { 'Root'; break } '^/providers/Microsoft.Management/managementGroups/' { 'ManagementGroup'; break } '^/subscriptions/[^/]+$' { 'Subscription'; break } '^/subscriptions/[^/]+/resourceGroups/[^/]+$' { 'ResourceGroup'; break } default { 'Resource' } } } $ra = [System.Collections.Generic.List[object]]::new() try { foreach ($s in $subs) { try { Set-AzContext -Subscription $s.Id -Tenant $TenantId -WarningAction SilentlyContinue | Out-Null $done = @{} foreach ($a in Get-AzRoleAssignment -WarningAction SilentlyContinue) { if ($done.ContainsKey($a.RoleAssignmentId)) { continue } $done[$a.RoleAssignmentId] = 1 $ra.Add([pscustomobject]@{ subscription_name = $s.Name; subscription_id = $s.Id; role = $a.RoleDefinitionName principal_name = $a.DisplayName; sign_in_name = $a.SignInName; principal_type = $a.ObjectType principal_id = $a.ObjectId; scope = $a.Scope; scope_level = (Get-ScopeLevel $a.Scope) assignment_id = $a.RoleAssignmentId }) } } catch { Write-Warning ("RBAC read failed for {0}: {1}" -f $s.Name, $_.Exception.Message) } } } finally { Set-AzContext -Context $originalContext -WarningAction SilentlyContinue | Out-Null } Save-Csv 'rbac_assignments.csv' $ra $priv = 'Owner', 'Contributor', 'User Access Administrator', 'Role Based Access Control Administrator' Register-Finding -Check 'rbac_privileged_broad_scope' -Severity 'High' ` -Advice 'Owner / Contributor / access-admin roles at root, management group or subscription scope. Apply least privilege; use PIM / RG-level scope; prefer groups over users.' ` -Rows @($ra | Where-Object { $_.role -in $priv -and $_.scope_level -in 'Root', 'ManagementGroup', 'Subscription' } | ForEach-Object { [pscustomobject]@{ id = $_.assignment_id; name = ($_.principal_name, $_.principal_id | Where-Object { $_ } | Select-Object -First 1) subscriptionId = $_.subscription_id; role = $_.role; principalType = $_.principal_type signInName = $_.sign_in_name; scope = $_.scope; scopeLevel = $_.scope_level } }) Register-Finding -Check 'rbac_orphaned_assignments' -Severity 'Medium' ` -Advice "Assignments whose principal type is 'Unknown' (usually deleted users / SPs). Remove after confirming. False positives appear if you lack Entra directory read." ` -Rows @($ra | Where-Object { $_.principal_type -eq 'Unknown' } | ForEach-Object { [pscustomobject]@{ id = $_.assignment_id; name = $_.principal_id; subscriptionId = $_.subscription_id role = $_.role; scope = $_.scope; scopeLevel = $_.scope_level } }) } } # ---------- end of inventory part # ============================================================ cost data (Cost Management Query API - read-only POST queries) # Docs: https://learn.microsoft.com/rest/api/cost-management/query/usage (api-version 2025-03-01) $costApi = '2025-03-01' function Invoke-CostQuery { param([Parameter(Mandatory)][string]$SubscriptionId, [Parameter(Mandatory)][System.Collections.IDictionary]$Body, [string]$Api = $costApi) $payload = $Body | ConvertTo-Json -Depth 10 -Compress $path = "/subscriptions/$SubscriptionId/providers/Microsoft.CostManagement/query?api-version=$Api" $rows = [System.Collections.Generic.List[object]]::new() $columns = $null $next = $null do { $attempt = 0 while ($true) { $resp = if ($next) { Invoke-AzRestMethod -Uri $next -Method POST -Payload $payload } else { Invoke-AzRestMethod -Path $path -Method POST -Payload $payload } if ($resp.StatusCode -in 429, 503 -and $attempt -lt 6) { $attempt++ $wait = 0 foreach ($h in 'x-ms-ratelimit-microsoft.costmanagement-qpu-retry-after', 'x-ms-ratelimit-microsoft.costmanagement-entity-retry-after', 'x-ms-ratelimit-microsoft.costmanagement-tenant-retry-after', 'x-ms-ratelimit-microsoft.consumption-retry-after', 'Retry-After') { $vals = $null try { if ($resp.Headers -and $resp.Headers.TryGetValues($h, [ref]$vals)) { $wait = [math]::Max($wait, [int]($vals | Select-Object -First 1)) } } catch { } } if ($wait -le 0) { $wait = 15 * $attempt } $wait = [math]::Min($wait, 120) Write-Warning ("Cost Management throttled (HTTP {0}). Waiting {1}s, retry {2}/6" -f $resp.StatusCode, $wait, $attempt) Start-Sleep -Seconds $wait continue } break } if ($resp.StatusCode -eq 204) { break } if ($resp.StatusCode -ge 400) { $msg = $resp.Content try { $e = $resp.Content | ConvertFrom-Json; if ($e.error.message) { $msg = "$($e.error.code): $($e.error.message)" } } catch { } throw ("HTTP {0}: {1}" -f $resp.StatusCode, $msg) } $json = $resp.Content | ConvertFrom-Json -Depth 20 if (-not $columns) { $columns = @($json.properties.columns | ForEach-Object { $_.name }) } foreach ($row in @($json.properties.rows)) { if ($null -ne $row) { $rows.Add($row) } } $next = $json.properties.nextLink Start-Sleep -Milliseconds 500 } while ($next) [pscustomobject]@{ Columns = @($columns); Rows = $rows } } function New-CostBody { param([string]$Timeframe, [string]$Granularity, [string[]]$Groups, [string[]]$Agg, [string]$From, [string]$To, [string]$Type = $CostType) $aggregation = [ordered]@{} foreach ($a in $Agg) { $aggregation["total$a"] = [ordered]@{ name = $a; function = 'Sum' } } $dataset = [ordered]@{ aggregation = $aggregation } if ($Granularity) { $dataset.granularity = $Granularity } if ($Groups) { $dataset.grouping = @($Groups | ForEach-Object { [ordered]@{ type = 'Dimension'; name = $_ } }) } $body = [ordered]@{ type = $Type; timeframe = $Timeframe; dataset = $dataset } if ($Timeframe -eq 'Custom') { $body.timePeriod = [ordered]@{ from = $From; to = $To } } return $body } function ConvertFrom-CostResult { param($Result, [string]$Period, $Sub, [switch]$Daily) $ix = @{} for ($i = 0; $i -lt $Result.Columns.Count; $i++) { $ix[[string]$Result.Columns[$i]] = $i } $costCol = @('Cost', 'PreTaxCost') | Where-Object { $ix.ContainsKey($_) } | Select-Object -First 1 foreach ($row in $Result.Rows) { $cost = if ($costCol) { [double]$row[$ix[$costCol]] } else { 0 } $usd = if ($ix.ContainsKey('CostUSD')) { [math]::Round([double]$row[$ix['CostUSD']], 4) } else { $null } $o = [ordered]@{} if ($Daily) { $v = $row[$ix['UsageDate']] $o.date = if ($v -is [datetime]) { $v.ToString('yyyy-MM-dd') } elseif ([string]$v -match '^(\d{4})-?(\d{2})-?(\d{2})') { "$($Matches[1])-$($Matches[2])-$($Matches[3])" } else { [string]$v } } else { $o.period = $Period $o.resource_id = if ($ix.ContainsKey('ResourceId')) { ([string]$row[$ix['ResourceId']]).ToLower() } else { '' } } $o.subscription_id = $Sub.Id $o.subscription_name = $Sub.Name $o.service_name = if ($ix.ContainsKey('ServiceName')) { [string]$row[$ix['ServiceName']] } else { '' } $o.cost = [math]::Round($cost, 4) $o.cost_usd = $usd $o.currency = if ($ix.ContainsKey('Currency')) { [string]$row[$ix['Currency']] } else { '' } [pscustomobject]$o } } function ConvertFrom-CostGeneric { # Fields: output column -> Cost Management column. Adds 'month' (yyyy-MM) when the result has a date column. param($Result, $Sub, [System.Collections.IDictionary]$Fields) $ix = @{} for ($i = 0; $i -lt $Result.Columns.Count; $i++) { $ix[[string]$Result.Columns[$i]] = $i } $costCol = @('Cost', 'PreTaxCost') | Where-Object { $ix.ContainsKey($_) } | Select-Object -First 1 $dateCol = @('BillingMonth', 'UsageDate') | Where-Object { $ix.ContainsKey($_) } | Select-Object -First 1 foreach ($row in $Result.Rows) { $o = [ordered]@{} if ($dateCol) { $v = $row[$ix[$dateCol]] # ConvertFrom-Json may already have turned ISO dates into [datetime] $o.month = if ($v -is [datetime]) { $v.ToString('yyyy-MM') } elseif ([string]$v -match '^(\d{4})-?(\d{2})') { "$($Matches[1])-$($Matches[2])" } else { [string]$v } } $o.subscription_id = $Sub.Id $o.subscription_name = $Sub.Name foreach ($k in $Fields.Keys) { $c = $Fields[$k]; $o[$k] = if ($ix.ContainsKey($c)) { [string]$row[$ix[$c]] } else { '' } } if ($o.Contains('resource_id')) { $o.resource_id = ([string]$o.resource_id).ToLower() } $o.cost = if ($costCol) { [math]::Round([double]$row[$ix[$costCol]], 4) } else { 0 } $o.cost_usd = if ($ix.ContainsKey('CostUSD')) { [math]::Round([double]$row[$ix['CostUSD']], 4) } else { $null } $o.currency = if ($ix.ContainsKey('Currency')) { [string]$row[$ix['Currency']] } else { '' } [pscustomobject]$o } } $costMonthly = [System.Collections.Generic.List[object]]::new() $costMeter = [System.Collections.Generic.List[object]]::new() $costPricing = [System.Collections.Generic.List[object]]::new() $costRes = [System.Collections.Generic.List[object]]::new() $costDaily = [System.Collections.Generic.List[object]]::new() $costStatus = [System.Collections.Generic.List[object]]::new() if (-not $SkipCost) { Write-Host ("Collecting cost data ({0}, last month + month to date + last {1} days) ..." -f $CostType, $CostDays) -ForegroundColor Cyan # Not every agreement type supports every column; the first shape that works is used for the subscription. # Variants go from richest to most basic; Azure's error message for each failed variant is kept in cost_status.csv. $shapes = @( @{ Api = '2025-03-01'; Type = $CostType; Gran = 'None'; Agg = @('Cost', 'CostUSD'); Groups = @('ResourceId', 'ServiceName') }, @{ Api = '2025-03-01'; Type = $CostType; Gran = 'None'; Agg = @('Cost'); Groups = @('ResourceId', 'ServiceName') }, @{ Api = '2025-03-01'; Type = $CostType; Gran = 'None'; Agg = @('Cost'); Groups = @('ResourceId') }, @{ Api = '2025-03-01'; Type = $CostType; Gran = 'None'; Agg = @('PreTaxCost'); Groups = @('ResourceId') }, @{ Api = '2023-11-01'; Type = $CostType; Gran = 'None'; Agg = @('Cost'); Groups = @('ResourceId', 'ServiceName') }, @{ Api = '2023-11-01'; Type = $CostType; Gran = 'Monthly'; Agg = @('Cost'); Groups = @('ResourceId') }, @{ Api = '2023-11-01'; Type = 'ActualCost'; Gran = 'None'; Agg = @('Cost'); Groups = @('ResourceId') }, @{ Api = '2023-11-01'; Type = 'Usage'; Gran = 'None'; Agg = @('PreTaxCost'); Groups = @('ResourceId') } ) # Explicit date ranges (timeframe 'Custom'): some agreements reject the named timeframes # such as TheLastMonth ("timeframe TheLastMonth is currently not supported"). $todayUtc = (Get-Date).ToUniversalTime().Date $monthStart = Get-Date -Year $todayUtc.Year -Month $todayUtc.Month -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0 $lastFrom = $monthStart.AddMonths(-1).ToString('yyyy-MM-ddT00:00:00Z') $lastTo = $monthStart.AddDays(-1).ToString('yyyy-MM-ddT23:59:59Z') $mtdFrom = $monthStart.ToString('yyyy-MM-ddT00:00:00Z') $mtdTo = $todayUtc.ToString('yyyy-MM-ddT23:59:59Z') $dailyFrom = $todayUtc.AddDays(-$CostDays).ToString('yyyy-MM-ddT00:00:00Z') $dailyTo = $todayUtc.AddDays(-1).ToString('yyyy-MM-ddT23:59:59Z') $monthsFrom = $monthStart.AddMonths(-$CostMonths).ToString('yyyy-MM-ddT00:00:00Z') Write-Host (" Last month {0} to {1}, month to date {2} to {3}" -f $lastFrom.Substring(0, 10), $lastTo.Substring(0, 10), $mtdFrom.Substring(0, 10), $mtdTo.Substring(0, 10)) foreach ($s in $subs) { $st = [ordered]@{ subscription_id = $s.Id; subscription_name = $s.Name; status = 'OK'; currency = '' last_month = $null; month_to_date = $null; cost_type = $CostType; columns = ''; details = '' } try { $shape = $null; $last = $null; $errs = [System.Collections.Generic.List[string]]::new() foreach ($sh in $shapes) { try { $last = Invoke-CostQuery -SubscriptionId $s.Id -Api $sh.Api -Body (New-CostBody -Timeframe 'Custom' -From $lastFrom -To $lastTo -Granularity $sh.Gran -Groups $sh.Groups -Agg $sh.Agg -Type $sh.Type) $shape = $sh; break } catch { if ($_.Exception.Message -notmatch '^HTTP 400') { throw } $errs.Add(("[{0} {1} {2}/{3}] {4}" -f $sh.Api, $sh.Type, ($sh.Agg -join '+'), ($sh.Groups -join '+'), $_.Exception.Message)) } } if (-not $shape) { $distinct = @($errs | ForEach-Object { ($_ -replace '^\[[^\]]+\] ', '') -replace '\s*\(Request ID: [^)]*\)', '' } | Select-Object -Unique) throw ('Every query variant was rejected (HTTP 400). Azure said: ' + ($distinct -join ' | ')) } if ($errs.Count) { Write-Host (" {0}: using fallback query [{1} {2} {3}]" -f $s.Name, $sh.Api, $shape.Type, ($shape.Agg -join '+')) -ForegroundColor DarkYellow } $st.cost_type = $shape.Type $st.columns = "$($shape.Api) " + (($shape.Agg + $shape.Groups) -join ',') $lastRows = @(ConvertFrom-CostResult -Result $last -Period 'last_month' -Sub $s) $mtd = Invoke-CostQuery -SubscriptionId $s.Id -Api $shape.Api -Body (New-CostBody -Timeframe 'Custom' -From $mtdFrom -To $mtdTo -Granularity $shape.Gran -Groups $shape.Groups -Agg $shape.Agg -Type $shape.Type) $mtdRows = @(ConvertFrom-CostResult -Result $mtd -Period 'month_to_date' -Sub $s) $dGroups = @($shape.Groups | Where-Object { $_ -eq 'ServiceName' }) $daily = Invoke-CostQuery -SubscriptionId $s.Id -Api $shape.Api -Body (New-CostBody -Timeframe 'Custom' -Granularity 'Daily' -Groups $dGroups -Agg $shape.Agg -From $dailyFrom -To $dailyTo -Type $shape.Type) $dayRows = @(ConvertFrom-CostResult -Result $daily -Sub $s -Daily) $lastRows + $mtdRows | ForEach-Object { $costRes.Add($_) } $dayRows | ForEach-Object { $costDaily.Add($_) } # Extra detail. Each dataset is optional: a failure is recorded in 'details' and the run continues. $svcGroup = @($shape.Groups | Where-Object { $_ -eq 'ServiceName' }) $extras = @( @{ Key = 'monthly'; List = $costMonthly; Fields = [ordered]@{ service_name = 'ServiceName' } Body = (New-CostBody -Timeframe 'Custom' -From $monthsFrom -To $mtdTo -Granularity 'Monthly' -Groups $svcGroup -Agg $shape.Agg -Type $shape.Type) }, @{ Key = 'meter'; List = $costMeter; Fields = [ordered]@{ resource_id = 'ResourceId'; meter = 'Meter' } Body = (New-CostBody -Timeframe 'Custom' -From $lastFrom -To $lastTo -Granularity $shape.Gran -Groups @('ResourceId', 'Meter') -Agg $shape.Agg -Type $shape.Type) }, @{ Key = 'pricing'; List = $costPricing; Fields = [ordered]@{ pricing_model = 'PricingModel'; charge_type = 'ChargeType' } Body = (New-CostBody -Timeframe 'Custom' -From $lastFrom -To $lastTo -Granularity $shape.Gran -Groups @('PricingModel', 'ChargeType') -Agg $shape.Agg -Type $shape.Type) } ) $det = @() foreach ($x in $extras) { try { $r = Invoke-CostQuery -SubscriptionId $s.Id -Api $shape.Api -Body $x.Body $n = 0; foreach ($o in @(ConvertFrom-CostGeneric -Result $r -Sub $s -Fields $x.Fields)) { $x.List.Add($o); $n++ } $det += "$($x.Key): $n rows" } catch { $det += "$($x.Key): FAILED " + ($_.Exception.Message -replace '\s*\(Request ID: [^)]*\)', '') Write-Warning (" {0}: {1} detail not available - {2}" -f $s.Name, $x.Key, ($_.Exception.Message -replace '\s*\(Request ID: [^)]*\)', '')) } } $st.details = $det -join '; ' $st.currency = (@($lastRows + $mtdRows + $dayRows | Where-Object currency | Group-Object currency | Sort-Object Count -Descending | Select-Object -First 1).Name) $st.last_month = [math]::Round(($lastRows | Measure-Object cost -Sum).Sum, 2) $st.month_to_date = [math]::Round(($mtdRows | Measure-Object cost -Sum).Sum, 2) Write-Host (" {0,-40} last month {1,14:N0} {3} month to date {2,14:N0} {3}" -f $s.Name, $st.last_month, $st.month_to_date, $st.currency) } catch { $m = $_.Exception.Message $st.status = if ($m -match '^HTTP (401|403)') { "NO ACCESS: $m (needs Cost Management Reader or Reader; for CSP the partner must enable cost visibility)" } else { "FAILED: $m" } Write-Warning ("Cost data for {0}: {1}" -f $s.Name, $st.status) } $costStatus.Add([pscustomobject]$st) } Save-Csv 'cost_by_resource.csv' $costRes Save-Csv 'cost_daily.csv' $costDaily Save-Csv 'cost_status.csv' $costStatus Save-Csv 'cost_monthly.csv' $costMonthly Save-Csv 'cost_by_meter.csv' $costMeter Save-Csv 'cost_by_pricing.csv' $costPricing } # ============================================================ write findings + metadata $sevOrder = @{ Critical = 0; High = 1; Medium = 2; Low = 3; Info = 4; Varies = 5 } if (-not $CostOnly) { Save-Csv 'findings_summary.csv' ($summary | Sort-Object @{ e = { $sevOrder[[string]$_.severity] } }, @{ e = 'count'; Descending = $true }) Save-Csv 'findings_all.csv' ($allFindings | Sort-Object @{ e = { if ($sevOrder.ContainsKey([string]$_.severity)) { $sevOrder[[string]$_.severity] } else { 9 } } }, check) } if ($script:ParseErrors) { Write-Warning "$($script:ParseErrors) JSON fragments could not be parsed; some relationships/tags may be missing." } [ordered]@{ script_version = $ScriptVersion generated_utc = (Get-Date).ToUniversalTime().ToString('o') tenant_id = $TenantId account = $ctx.Account.Id subscriptions = $subs.Count resource_groups = @($rgFlat).Count resources = $resources.Count relationships = $edges.Count findings = $allFindings.Count include_rbac = [bool]$IncludeRbac json_parse_errors = $script:ParseErrors cost_type = if ($SkipCost) { $null } else { $CostType } cost_rows = $costRes.Count cost_currency = (@($costStatus | Where-Object currency | Group-Object currency | Sort-Object Count -Descending | Select-Object -First 1).Name) duration_seconds = [math]::Round($timer.Elapsed.TotalSeconds, 1) cost_only = [bool]$CostOnly } | ConvertTo-Json | Set-Content (Join-Path $OutputPath ($(if ($CostOnly) { 'cost_metadata.json' } else { 'run_metadata.json' }))) -Encoding utf8NoBOM # ============================================================ zip $zip = "$OutputPath.zip" if (Test-Path $zip) { Remove-Item $zip -Force } # only removes this run's own zip Compress-Archive -Path (Join-Path $OutputPath '*') -DestinationPath $zip Write-Host '' Write-Host ("Done in {0:N0}s." -f $timer.Elapsed.TotalSeconds) -ForegroundColor Green Write-Host " Folder : $OutputPath" Write-Host " Zip : $zip" Write-Host ' Cloud Shell: Manage files > Download, then enter the zip path above.'