Public/DrawAzure.ps1
|
#Requires -Version 7.0 # ============================================================ # DrawManagement — Azure Resource Catalogue # # Maps Azure ARM resource types to draw.io icons and to functional # architecture tiers, plus the filtering rules that decide which # resources are worth drawing at all. # # Ported from New-AzureArchitectureDiagram.ps1 (iconMap, tierMap, # excludedTypes, managedRgPatterns, childTypes and their helpers). # # The icon paths reference draw.io's BUILT-IN azure2 / mscae stencil # libraries (img/lib/...). draw.io resolves them at render time, so the # output file stays self-contained with no external URLs and no # embedded image data. # # This file contains reference data only — it never calls Azure. Feed it # resource objects you already fetched (Get-AzResource and friends), or # plain type strings. # ============================================================ # ── Icon map: ARM type → draw.io stencil ───────────────────────────── # Mscae = $true selects the older mscae stencil set, which needs # sketch=0 in the style string. $script:DrawAzureIcons = [ordered]@{ # -- Compute --------------------------------------------------------- 'Microsoft.Compute/virtualMachines' = @{ Path = 'img/lib/azure2/compute/Virtual_Machine.svg'; Mscae = $false } 'Microsoft.Compute/virtualMachineScaleSets' = @{ Path = 'img/lib/mscae/VM_Scale_Set.svg'; Mscae = $true } 'Microsoft.Compute/disks' = @{ Path = 'img/lib/azure2/compute/Disks.svg'; Mscae = $false } # -- Containers ------------------------------------------------------ 'Microsoft.ContainerService/managedClusters' = @{ Path = 'img/lib/azure2/containers/Kubernetes_Services.svg'; Mscae = $false } 'Microsoft.ContainerRegistry/registries' = @{ Path = 'img/lib/azure2/containers/Container_Registries.svg'; Mscae = $false } # -- Networking ------------------------------------------------------ # [FIX-34] virtualNetworks and networkInterfaces both pointed at # Subnet.svg. draw.io ships a glyph for each, so a VNet was drawn as one # of its own subnets and a NIC as another — wrong picture, no error. 'Microsoft.Network/virtualNetworks' = @{ Path = 'img/lib/azure2/networking/Virtual_Networks.svg'; Mscae = $false } 'Microsoft.Network/networkInterfaces' = @{ Path = 'img/lib/azure2/networking/Network_Interfaces.svg'; Mscae = $false } 'Microsoft.Network/publicIPAddresses' = @{ Path = 'img/lib/azure2/networking/Public_IP_Addresses.svg'; Mscae = $false } 'Microsoft.Network/networkSecurityGroups' = @{ Path = 'img/lib/azure2/networking/Network_Security_Groups.svg'; Mscae = $false } 'Microsoft.Network/virtualNetworkGateways' = @{ Path = 'img/lib/azure2/networking/Virtual_Network_Gateways.svg'; Mscae = $false } 'Microsoft.Network/natGateways' = @{ Path = 'img/lib/azure2/networking/NAT.svg'; Mscae = $false } 'Microsoft.Network/loadBalancers' = @{ Path = 'img/lib/azure2/networking/Load_Balancers.svg'; Mscae = $false } 'Microsoft.Network/applicationGateways' = @{ Path = 'img/lib/azure2/networking/Application_Gateways.svg'; Mscae = $false } 'Microsoft.Network/frontDoors' = @{ Path = 'img/lib/azure2/networking/Front_Doors.svg'; Mscae = $false } 'Microsoft.Cdn/profiles' = @{ Path = 'img/lib/azure2/networking/CDN_Profiles.svg'; Mscae = $false } 'Microsoft.Network/privateLinkServices' = @{ Path = 'img/lib/azure2/networking/Private_Link_Service.svg'; Mscae = $false } 'Microsoft.Network/dnsResolvers' = @{ Path = 'img/lib/azure2/networking/DNS_Private_Resolver.svg'; Mscae = $false } 'Microsoft.Network/privateEndpoints' = @{ Path = 'img/lib/azure2/other/Private_Endpoints.svg'; Mscae = $false } 'Microsoft.Network/dnsZones' = @{ Path = 'img/lib/mscae/DNS_Private_Zones.svg'; Mscae = $true } # -- Storage --------------------------------------------------------- 'Microsoft.Storage/storageAccounts' = @{ Path = 'img/lib/azure2/storage/Storage_Accounts.svg'; Mscae = $false } # -- Databases ------------------------------------------------------- 'Microsoft.Sql/servers' = @{ Path = 'img/lib/azure2/databases/SQL_Server.svg'; Mscae = $false } 'Microsoft.Sql/servers/elasticPools' = @{ Path = 'img/lib/azure2/databases/SQL_Elastic_Pools.svg'; Mscae = $false } 'Microsoft.Sql/servers/databases' = @{ Path = 'img/lib/mscae/SQL_Database_generic.svg'; Mscae = $true } # [FIX-34] Cosmos DB was drawn with the SQL Server glyph. 'Microsoft.DocumentDb/databaseAccounts' = @{ Path = 'img/lib/azure2/databases/Azure_Cosmos_DB.svg'; Mscae = $false } 'Microsoft.DBforPostgreSQL/servers' = @{ Path = 'img/lib/azure2/databases/Azure_Database_PostgreSQL_Server.svg'; Mscae = $false } 'Microsoft.DBforPostgreSQL/flexibleServers' = @{ Path = 'img/lib/azure2/databases/Azure_Database_PostgreSQL_Server.svg'; Mscae = $false } 'Microsoft.DBforMySQL/servers' = @{ Path = 'img/lib/azure2/databases/Azure_Database_MySQL_Server.svg'; Mscae = $false } 'Microsoft.DBforMySQL/flexibleServers' = @{ Path = 'img/lib/azure2/databases/Azure_Database_MySQL_Server.svg'; Mscae = $false } # -- Security -------------------------------------------------------- 'Microsoft.KeyVault/vaults' = @{ Path = 'img/lib/azure2/security/Key_Vaults.svg'; Mscae = $false } 'Microsoft.Security/defenderForCloud' = @{ Path = 'img/lib/azure2/security/Azure_Defender.svg'; Mscae = $false } 'Microsoft.Security/securitySolutions' = @{ Path = 'img/lib/mscae/Azure_Sentinel.svg'; Mscae = $true } # -- Identity -------------------------------------------------------- 'Microsoft.ManagedIdentity/userAssignedIdentities' = @{ Path = 'img/lib/azure2/identity/Managed_Identities.svg'; Mscae = $false } # -- Web / App Services ---------------------------------------------- # [FIX-34] Microsoft.Web/sites is the type for BOTH web apps and function # apps — the two are told apart by the resource's 'kind', which this # catalogue never sees. Mapping it to Function_Apps.svg therefore drew # every App Service as a function app. App_Services.svg is the honest # choice for a type-only lookup. 'Microsoft.Web/sites' = @{ Path = 'img/lib/azure2/app_services/App_Services.svg'; Mscae = $false } 'Microsoft.Web/serverFarms' = @{ Path = 'img/lib/azure2/app_services/App_Service_Plans.svg'; Mscae = $false } 'Microsoft.Web/staticSites' = @{ Path = 'img/lib/azure2/preview/Static_Apps.svg'; Mscae = $false } # -- Messaging / Integration ----------------------------------------- 'Microsoft.ServiceBus/namespaces' = @{ Path = 'img/lib/azure2/integration/Service_Bus.svg'; Mscae = $false } 'Microsoft.EventHub/namespaces' = @{ Path = 'img/lib/azure2/iot/Event_Hubs.svg'; Mscae = $false } 'Microsoft.EventGrid/topics' = @{ Path = 'img/lib/azure2/integration/Event_Grid_Topics.svg'; Mscae = $false } 'Microsoft.Logic/workflows' = @{ Path = 'img/lib/azure2/integration/Logic_Apps.svg'; Mscae = $false } 'Microsoft.NotificationHubs/namespaces' = @{ Path = 'img/lib/azure2/app_services/Notification_Hubs.svg'; Mscae = $false } 'Microsoft.SignalRService/signalR' = @{ Path = 'img/lib/azure2/web/SignalR.svg'; Mscae = $false } # -- Cache ----------------------------------------------------------- 'Microsoft.Cache/redis' = @{ Path = 'img/lib/mscae/Cache_Redis_Product.svg'; Mscae = $true } # -- AI / ML --------------------------------------------------------- 'Microsoft.CognitiveServices/accounts' = @{ Path = 'img/lib/azure2/ai_machine_learning/Azure_OpenAI.svg'; Mscae = $false } # -- Monitoring / Management ----------------------------------------- 'Microsoft.Monitor/monitorWorkspaces' = @{ Path = 'img/lib/azure2/management_governance/Monitor.svg'; Mscae = $false } 'Microsoft.OperationalInsights/workspaces' = @{ Path = 'img/lib/azure2/analytics/Log_Analytics_Workspaces.svg'; Mscae = $false } 'Microsoft.Insights/components' = @{ Path = 'img/lib/azure2/management_governance/Application_Insights.svg'; Mscae = $false } 'Microsoft.RecoveryServices/vaults' = @{ Path = 'img/lib/azure2/management_governance/Recovery_Services_Vaults.svg'; Mscae = $false } 'Microsoft.DataProtection/backupVaults' = @{ Path = 'img/lib/azure2/other/Backup_Vault.svg'; Mscae = $false } # -- DevOps ---------------------------------------------------------- 'Microsoft.DevOps/projects' = @{ Path = 'img/lib/mscae/Azure_DevOps.svg'; Mscae = $true } } # Neutral dashed chip for unmapped types — keeps the "not in the catalogue" # signal visible without a giant generic cloud dominating the page. $script:DrawAzureFallbackStyle = 'rounded=1;whiteSpace=wrap;html=1;fillColor=#eef3f9;strokeColor=#6c8ebf;dashed=1;' + 'dashPattern=3 3;fontColor=#444444;verticalLabelPosition=bottom;verticalAlign=top;' + 'align=center;fontSize=9;fontStyle=2;' # ── Tier map: ARM type → functional architecture tier ──────────────── $script:DrawAzureTiers = @{ 'Microsoft.Network/applicationGateways' = 'Edge' 'Microsoft.Network/loadBalancers' = 'Edge' 'Microsoft.Network/frontDoors' = 'Edge' 'Microsoft.Cdn/profiles' = 'Edge' 'Microsoft.Network/publicIPAddresses' = 'Edge' 'Microsoft.Network/virtualNetworkGateways' = 'Edge' 'Microsoft.Network/natGateways' = 'Edge' 'Microsoft.Network/privateEndpoints' = 'Edge' 'Microsoft.Network/privateLinkServices' = 'Edge' 'Microsoft.Compute/virtualMachines' = 'App' 'Microsoft.Compute/virtualMachineScaleSets' = 'App' 'Microsoft.ContainerService/managedClusters' = 'App' 'Microsoft.ContainerRegistry/registries' = 'App' 'Microsoft.Web/sites' = 'App' 'Microsoft.Web/staticSites' = 'App' 'Microsoft.Web/serverFarms' = 'App' 'Microsoft.CognitiveServices/accounts' = 'App' 'Microsoft.Sql/servers' = 'Data' 'Microsoft.Sql/servers/databases' = 'Data' 'Microsoft.DocumentDb/databaseAccounts' = 'Data' 'Microsoft.Storage/storageAccounts' = 'Data' 'Microsoft.Cache/redis' = 'Data' 'Microsoft.DBforPostgreSQL/servers' = 'Data' 'Microsoft.DBforPostgreSQL/flexibleServers' = 'Data' 'Microsoft.DBforMySQL/servers' = 'Data' 'Microsoft.DBforMySQL/flexibleServers' = 'Data' 'Microsoft.ServiceBus/namespaces' = 'Integration' 'Microsoft.EventHub/namespaces' = 'Integration' 'Microsoft.EventGrid/topics' = 'Integration' 'Microsoft.NotificationHubs/namespaces' = 'Integration' 'Microsoft.SignalRService/signalR' = 'Integration' 'Microsoft.Logic/workflows' = 'Integration' 'Microsoft.KeyVault/vaults' = 'Security' 'Microsoft.Security/defenderForCloud' = 'Security' 'Microsoft.Security/securitySolutions' = 'Security' 'Microsoft.ManagedIdentity/userAssignedIdentities' = 'Identity' 'Microsoft.OperationalInsights/workspaces' = 'Observability' 'Microsoft.Monitor/monitorWorkspaces' = 'Observability' 'Microsoft.Insights/components' = 'Observability' 'Microsoft.RecoveryServices/vaults' = 'Observability' 'Microsoft.DataProtection/backupVaults' = 'Observability' } # Tier presentation: draw order, lane colour, and the label for the flow # arrow leaving that tier. Ordered — enumeration order is the lane order. $script:DrawAzureTierInfo = [ordered]@{ Edge = @{ Color = '#FFE6CC'; Flow = 'traffic' } App = @{ Color = '#DAE8FC'; Flow = 'process' } Integration = @{ Color = '#E1D5E7'; Flow = 'events' } Data = @{ Color = '#D5E8D4'; Flow = 'persist' } Security = @{ Color = '#F8CECC'; Flow = 'secrets' } Identity = @{ Color = '#FFF2CC'; Flow = 'auth' } Observability = @{ Color = '#D4E1F5'; Flow = 'telemetry' } Other = @{ Color = '#F5F5F5'; Flow = '' } } # Implementation-detail types — hidden by default. They clutter a diagram # without adding architectural value: disks belong to VMs, NICs are # implicit, NSGs already show on subnets, alerts are configuration. $script:DrawAzureExcludedTypes = @( 'Microsoft.Compute/disks' 'Microsoft.Compute/snapshots' 'Microsoft.Compute/virtualMachines/extensions' 'Microsoft.Network/networkInterfaces' 'Microsoft.Network/networkSecurityGroups' 'Microsoft.Network/publicIPAddresses' 'Microsoft.Network/privateDnsZones' 'Microsoft.Network/privateDnsZones/virtualNetworkLinks' 'Microsoft.Network/routeTables' 'Microsoft.Insights/components' 'Microsoft.Insights/activityLogAlerts' 'Microsoft.Insights/actionGroups' 'Microsoft.Insights/scheduledqueryrules' 'Microsoft.Insights/metricAlerts' 'microsoft.alertsmanagement/smartDetectorAlertRules' 'Microsoft.OperationalInsights/solutions' 'Microsoft.ManagedIdentity/userAssignedIdentities' 'Microsoft.Resources/deploymentScripts' ) # Child types folded into their parent rather than drawn separately. # # [FIX-33] Only a GENUINELY NESTED ARM type belongs here — one whose type # has three segments (Provider/parent/child) and whose parent is therefore # the first two. Select-DrawAzureResource finds the parent by stripping the # last two segments off the child's Id, and that is the only shape of type # for which that arithmetic is true. # # 'Microsoft.Web/sites' = 'Microsoft.Web/serverFarms' was listed here and is # neither: a web app is a TOP-LEVEL resource that names its plan in the # serverFarmId property, not in its Id. Stripping two segments off # /…/providers/Microsoft.Web/sites/app1 yields /…/providers/Microsoft.Web, # which is no resource's Id. Every App Service was therefore dropped from # Resources and filed under a key no caller could look up — the whole tier # vanished from the diagram with no warning and a success exit. $script:DrawAzureChildTypes = @{ 'Microsoft.Sql/servers/databases' = 'Microsoft.Sql/servers' 'Microsoft.Sql/servers/elasticPools' = 'Microsoft.Sql/servers' } # Resource-group names that indicate platform-managed groups (AKS node # RGs, Databricks workspaces, …). Auto-generated, not part of a design. $script:DrawAzureManagedRgPatterns = @( '^MC_' '^AKS_' '^databricks-rg-' '^NetworkWatcherRG$' '^DefaultResourceGroup-' '^cloud-shell-storage-' '^microsoft-network$' ) # ───────────────────────────────────────────────────────────────────── # PUBLIC FUNCTIONS # ───────────────────────────────────────────────────────────────────── function Get-DrawAzureStyle { <# .SYNOPSIS Returns the draw.io style string for an Azure resource type. .DESCRIPTION Looks the ARM type up in the built-in icon catalogue and builds an image style referencing draw.io's bundled azure2 / mscae stencils. Unmapped types get a neutral dashed chip so they stay visible as "not catalogued" rather than silently vanishing. .PARAMETER ResourceType ARM resource type, e.g. 'Microsoft.Compute/virtualMachines'. Matching is case-insensitive. .PARAMETER LabelBelow Force the label under the glyph. Recommended for grid layouts, where a centred label would sit on top of the icon. .EXAMPLE $style = Get-DrawAzureStyle -ResourceType 'Microsoft.Compute/virtualMachines' Add-DrawShape -Page $p -Label 'web-01' -Style $style .OUTPUTS [string] draw.io style. #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory, ValueFromPipeline)][ValidateNotNullOrEmpty()][string] $ResourceType, [Parameter()][switch] $LabelBelow ) process { $entry = $null foreach ($k in $script:DrawAzureIcons.Keys) { if ($k -eq $ResourceType) { $entry = $script:DrawAzureIcons[$k]; break } } if ($null -eq $entry) { $style = $script:DrawAzureFallbackStyle } else { $sketch = if ($entry.Mscae) { 'sketch=0;' } else { '' } $style = "image;${sketch}aspect=fixed;html=1;points=[];align=center;" + "fontSize=12;image=$($entry.Path);" } if ($LabelBelow -and $style -notmatch 'verticalLabelPosition') { $style = Join-DrawStyle $style 'verticalLabelPosition=bottom;verticalAlign=top;align=center;' } return $style } } function Get-DrawAzureTier { <# .SYNOPSIS Returns the functional architecture tier for an Azure resource type. .DESCRIPTION Maps an ARM type to one of Edge, App, Integration, Data, Security, Identity, Observability, or Other for anything unrecognised. Use it to group resources into lanes with Set-DrawLayeredLayout. .PARAMETER ResourceType ARM resource type. Matching is case-insensitive. .EXAMPLE Get-DrawAzureTier -ResourceType 'Microsoft.Sql/servers' # -> Data .EXAMPLE $byTier = $resources | Group-Object { Get-DrawAzureTier $_.ResourceType } .OUTPUTS [string] #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory, ValueFromPipeline)][ValidateNotNullOrEmpty()][string] $ResourceType ) process { foreach ($k in $script:DrawAzureTiers.Keys) { if ($k -eq $ResourceType) { return $script:DrawAzureTiers[$k] } } return 'Other' } } function Get-DrawAzureTierInfo { <# .SYNOPSIS Lists the architecture tiers with their draw order, colour and flow label. .DESCRIPTION Returns tiers in canonical top-to-bottom order, which is the order lanes should appear in a layered diagram. Feed straight into Set-DrawLayeredLayout for consistent tier colouring. .PARAMETER Tier Return only this tier. .EXAMPLE Get-DrawAzureTierInfo | ForEach-Object { @{ Name = $_.Name; Cells = $byTier[$_.Name]; FillColor = $_.Color } } .OUTPUTS [PSCustomObject] with Name, Order, Color, FlowLabel. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter()][string] $Tier ) $i = 0 foreach ($name in $script:DrawAzureTierInfo.Keys) { $i++ if (-not [string]::IsNullOrWhiteSpace($Tier) -and $name -ne $Tier) { continue } $info = $script:DrawAzureTierInfo[$name] [PSCustomObject]@{ PSTypeName = 'DrawManagement.AzureTier' Name = $name Order = $i Color = $info.Color FlowLabel = $info.Flow } } } function Get-DrawAzureCatalog { <# .SYNOPSIS Lists every Azure resource type the module has an icon for. .DESCRIPTION The discovery command for this catalogue — run it to find out whether a type is mapped before assuming an icon will appear. .PARAMETER Tier Show only types belonging to this tier. .PARAMETER ResourceType Wildcard filter on the ARM type, e.g. 'Microsoft.Network/*'. .EXAMPLE Get-DrawAzureCatalog -Tier Data | Format-Table .EXAMPLE Get-DrawAzureCatalog -ResourceType 'Microsoft.Network/*' .OUTPUTS [PSCustomObject] with ResourceType, Tier, IconPath, Mscae, Excluded. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter()][string] $Tier, [Parameter()][string] $ResourceType ) foreach ($type in $script:DrawAzureIcons.Keys) { if (-not [string]::IsNullOrWhiteSpace($ResourceType) -and $type -notlike $ResourceType) { continue } $t = Get-DrawAzureTier -ResourceType $type if (-not [string]::IsNullOrWhiteSpace($Tier) -and $t -ne $Tier) { continue } [PSCustomObject]@{ PSTypeName = 'DrawManagement.AzureCatalogEntry' ResourceType = $type Tier = $t IconPath = $script:DrawAzureIcons[$type].Path Mscae = $script:DrawAzureIcons[$type].Mscae Excluded = ($script:DrawAzureExcludedTypes -contains $type) } } } function Test-DrawAzureManagedResourceGroup { <# .SYNOPSIS Tests whether a resource-group name looks platform-managed. .DESCRIPTION Matches names Azure generates for you — AKS node pools (MC_*), Databricks workspaces, NetworkWatcherRG, Cloud Shell storage and similar. Those groups are infrastructure the platform created, not part of an architect's design, so they are normally left out. .PARAMETER Name Resource-group name to test. .EXAMPLE Test-DrawAzureManagedResourceGroup -Name 'MC_rg-aks_prod_westeurope' # -> True .OUTPUTS [bool] #> [CmdletBinding()] [OutputType([bool])] param( [Parameter(Mandatory, ValueFromPipeline)][AllowEmptyString()][string] $Name ) process { if ([string]::IsNullOrWhiteSpace($Name)) { return $false } foreach ($pattern in $script:DrawAzureManagedRgPatterns) { if ($Name -match $pattern) { return $true } } return $false } } function Select-DrawAzureResource { <# .SYNOPSIS Filters a resource list down to what is worth drawing. .DESCRIPTION Applies three rules in order: 1. drop resources in platform-managed resource groups 2. drop implementation-detail types (disks, NICs, alerts…) 3. fold nested child resources (SQL databases and elastic pools) into their parent Returns the kept resources plus a ChildrenByParent map, so the caller can list the folded children in the parent's tooltip. Both Resources and every ChildrenByParent value are plain arrays. Input is duck-typed: any object exposing ResourceType, Id and ResourceGroupName works, which is what Get-AzResource returns. This function never calls Azure itself. .PARAMETER Resource The resource objects to filter. .PARAMETER IncludeAll Skip rules 1 and 2 — keep everything except child folding. Use for audit or compliance views where completeness beats readability. .EXAMPLE $sel = Select-DrawAzureResource -Resource (Get-AzResource) foreach ($r in $sel.Resources) { $kids = $sel.ChildrenByParent[$r.Id] Add-DrawShape -Page $p -Label $r.Name ` -Style (Get-DrawAzureStyle $r.ResourceType -LabelBelow) ` -Tooltip "Children: $($kids.Count)" } .OUTPUTS [PSCustomObject] with Resources, ChildrenByParent, and the Excluded / Collapsed / ManagedResourceGroup counts. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( [Parameter(Mandatory, ValueFromPipeline)][AllowEmptyCollection()][object[]] $Resource, [Parameter()][switch] $IncludeAll ) begin { $inbox = New-Object 'System.Collections.Generic.List[object]' } process { foreach ($r in $Resource) { if ($null -ne $r) { $inbox.Add($r) } } } end { $childrenByParent = @{} $parentIdById = @{} # Index children by the parent Id implied by their ARM Id: strip the # last two segments (/<childType>/<childName>). foreach ($r in $inbox) { $type = [string](Get-DrawObjectProperty -InputObject $r -Name 'ResourceType') $id = [string](Get-DrawObjectProperty -InputObject $r -Name 'Id') if ([string]::IsNullOrWhiteSpace($type) -or [string]::IsNullOrWhiteSpace($id)) { continue } if (-not $script:DrawAzureChildTypes.ContainsKey($type)) { continue } # [FIX-33] The strip-two-segments rule above is only valid for a # genuinely nested type — Provider/parent/child, whose parent is # the first two segments. Fold anything else and the resource is # removed from the diagram and filed under an Id that belongs to # nothing. Refuse rather than delete silently. $typeParts = $type -split '/' if ($typeParts.Count -ne 3 -or $script:DrawAzureChildTypes[$type] -ne ($typeParts[0..1] -join '/')) { Write-Warning (("Select-DrawAzureResource: '{0}' is declared a child of '{1}', but only a nested " + "Provider/parent/child type can be folded by Id. Drawing it as a top-level resource.") -f $type, $script:DrawAzureChildTypes[$type]) continue } $parts = $id -split '/' if ($parts.Count -ge 4) { $parentIdById[$id] = ($parts[0..($parts.Count - 3)] -join '/') } } $kept = New-Object 'System.Collections.Generic.List[object]' [int]$nExcluded = 0; [int]$nCollapsed = 0; [int]$nManagedRg = 0 foreach ($r in $inbox) { $type = [string](Get-DrawObjectProperty -InputObject $r -Name 'ResourceType') $id = [string](Get-DrawObjectProperty -InputObject $r -Name 'Id') $rg = [string](Get-DrawObjectProperty -InputObject $r -Name 'ResourceGroupName') if (-not $IncludeAll -and (Test-DrawAzureManagedResourceGroup -Name $rg)) { $nManagedRg++ continue } if (-not $IncludeAll -and $script:DrawAzureExcludedTypes -contains $type) { $nExcluded++ continue } if (-not [string]::IsNullOrWhiteSpace($id) -and $parentIdById.ContainsKey($id)) { $parentKey = $parentIdById[$id] if (-not $childrenByParent.ContainsKey($parentKey)) { $childrenByParent[$parentKey] = New-Object 'System.Collections.Generic.List[object]' } $childrenByParent[$parentKey].Add($r) $nCollapsed++ continue } $kept.Add($r) } Write-Verbose ("Select-DrawAzureResource: kept=$($kept.Count) excluded=$nExcluded " + "collapsed=$nCollapsed managedRG=$nManagedRg") # [FIX-35] Hand out plain arrays, not List[object]. Resources was # already materialised with ToArray(); the ChildrenByParent values # were not, so the documented `$sel.ChildrenByParent[$r.Id]` lookup # returned a List[object] — and on PowerShell 7.6.6 the ordinary # defensive wrap `@($kids)` throws "Argument types do not match" on # that one generic type alone. The caller gets a mid-loop terminating # error on exactly the resources that HAVE children, which is the # minority, so a partially-drawn diagram is the usual outcome. $childrenOut = @{} foreach ($k in $childrenByParent.Keys) { $childrenOut[$k] = $childrenByParent[$k].ToArray() } [PSCustomObject]@{ PSTypeName = 'DrawManagement.AzureSelection' Resources = $kept.ToArray() ChildrenByParent = $childrenOut Excluded = $nExcluded Collapsed = $nCollapsed ManagedResourceGroup = $nManagedRg } } } function Add-DrawAzureResource { <# .SYNOPSIS Adds a shape for an Azure resource with the right icon applied. .DESCRIPTION Convenience wrapper over Add-DrawShape: resolves the icon from the ARM type, defaults the label to the resource name, and builds a tooltip from type / resource group / location. Everything else behaves exactly like Add-DrawShape. .PARAMETER Page The [DrawPage] to add the shape to. .PARAMETER Resource A resource object exposing Name, ResourceType, ResourceGroupName and Location — i.e. what Get-AzResource returns. Mutually exclusive with -ResourceType. .PARAMETER ResourceType ARM type, when you do not have a full resource object. .PARAMETER Label Overrides the label. Defaults to the resource's Name. .PARAMETER X Horizontal position. Default: 100. .PARAMETER Y Vertical position. Default: 100. .PARAMETER Width Shape width. Default: 60. .PARAMETER Height Shape height. Default: 60. .PARAMETER ParentId Parent container Id. Default: '1'. .PARAMETER Metadata Extra UserObject properties, merged over the defaults this function derives from the resource. .PARAMETER Tooltip Overrides the generated tooltip. .PARAMETER NoLabelBelow Keep the label centred on the icon instead of below it. .PARAMETER PassThru Return the created [DrawCell]. .EXAMPLE Get-AzResource | ForEach-Object { Add-DrawAzureResource -Page $p -Resource $_ -PassThru } .EXAMPLE Add-DrawAzureResource -Page $p -ResourceType 'Microsoft.Cache/redis' ` -Label 'session-cache' -X 200 -Y 120 .OUTPUTS [DrawCell] when -PassThru is specified. #> [CmdletBinding(DefaultParameterSetName = 'ByObject')] [OutputType([DrawCell])] param( [Parameter(Mandatory)][DrawPage] $Page, [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'ByObject')][object] $Resource, [Parameter(Mandatory, ParameterSetName = 'ByType')][ValidateNotNullOrEmpty()][string] $ResourceType, [Parameter()][string] $Label, [Parameter()][double] $X = 100, [Parameter()][double] $Y = 100, [Parameter()][ValidateRange(1, 99999)][double] $Width = 60, [Parameter()][ValidateRange(1, 99999)][double] $Height = 60, [Parameter()][string] $ParentId = '1', [Parameter()][hashtable] $Metadata = @{}, [Parameter()][string] $Tooltip, [Parameter()][switch] $NoLabelBelow, [Parameter()][switch] $PassThru ) process { if ($PSCmdlet.ParameterSetName -eq 'ByObject') { $type = [string](Get-DrawObjectProperty -InputObject $Resource -Name 'ResourceType') $name = [string](Get-DrawObjectProperty -InputObject $Resource -Name 'Name') $rg = [string](Get-DrawObjectProperty -InputObject $Resource -Name 'ResourceGroupName') $loc = [string](Get-DrawObjectProperty -InputObject $Resource -Name 'Location') } else { $type = $ResourceType $name = ''; $rg = ''; $loc = '' } if ([string]::IsNullOrWhiteSpace($type)) { throw ("Add-DrawAzureResource: could not determine the resource type. " + "Pass -ResourceType, or an object with a ResourceType property.") } $finalLabel = if (-not [string]::IsNullOrWhiteSpace($Label)) { $Label } else { $name } $style = Get-DrawAzureStyle -ResourceType $type -LabelBelow:(-not $NoLabelBelow) $finalTooltip = if (-not [string]::IsNullOrWhiteSpace($Tooltip)) { $Tooltip } else { $parts = @("Type: $type") if ($rg) { $parts += "Resource Group: $rg" } if ($loc) { $parts += "Location: $loc" } $parts -join ' | ' } # Caller-supplied metadata wins over the derived defaults. $meta = @{ azure_type = $type } if ($rg) { $meta['resource_group'] = $rg } if ($loc) { $meta['location'] = $loc } foreach ($k in $Metadata.Keys) { $meta[$k] = $Metadata[$k] } $cell = Add-DrawShape -Page $Page -Label $finalLabel -Style $style ` -X $X -Y $Y -Width $Width -Height $Height ` -ParentId $ParentId -Metadata $meta -Tooltip $finalTooltip -PassThru if ($PassThru) { return $cell } } } |