如何通过PowerShell从Azure资源ID中提取任意指定值
从Azure资源ID提取任意分段的通用方法
问题根源
你提取路由表名称失败的原因是原正则表达式要求匹配/routeTables/xxx/格式,但你的资源ID末尾是/routeTables/my-route,没有最后的斜杠,导致正则无法匹配到目标内容。
快速修正提取路由表名称
把正则改成适配末尾无斜杠的情况:
$route = [regex]::Match($RouteTableJson.ID, '/routeTables/([^/]+)(?:/|$)').Groups[1].Value
这里(?:/|$)表示匹配斜杠或者字符串结尾,是不捕获的分组,确保不管资源ID是否以斜杠结尾都能匹配到路由表名称。
通用提取函数(推荐)
如果需要频繁提取不同分段(订阅ID、资源组、路由表、资源名称等),可以写一个通用函数,避免重复写正则:
function Get-AzureResourceIdSegment { param( [Parameter(Mandatory=$true)] [string]$ResourceId, [Parameter(Mandatory=$true)] [string]$SegmentName ) # 按斜杠分割资源ID,过滤空字符串 $segments = $ResourceId -split '/' | Where-Object { $_ -ne '' } # 找到目标分段的索引 $index = $segments.IndexOf($SegmentName) if ($index -eq -1) { Write-Warning "资源ID中未找到分段 '$SegmentName'" return $null } # 返回目标分段的下一个元素(对应的值) return $segments[$index + 1] }
使用示例
针对你的资源ID False /subscriptions/ccccccccccccccc/resourceGroups/rg-mynetwork01/providers/Microsoft.Network/routeTables/my-route,先清理掉开头的False :
# 清理资源ID(去掉开头的"False ") $cleanedResourceId = $RouteTableJson.ID -replace '^False ', '' # 提取订阅ID $subscriptionId = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'subscriptions' # 提取资源组名称 $resourceGroup = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'resourceGroups' # 提取路由表名称 $routeTableName = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'routeTables' # 提取提供商名称 $provider = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'providers'
这样不管要提取哪个分段,只需要传入对应的分段名称即可,无需修改正则。
优化你的原脚本
原脚本中$RouteTableJson和$RouteJson重复定义了,可简化:
$subnet_config = Get-AzVirtualNetworkSubnetConfig -Name $subnet.Name -VirtualNetwork $vnet $RouteTableJson = $subnet_config.RouteTableText | ConvertFrom-Json # 清理资源ID $cleanedResourceId = $RouteTableJson.ID -replace '^False ', '' # 使用通用函数提取 $rg = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'resourceGroups' $route = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'routeTables' $subscription = Get-AzureResourceIdSegment -ResourceId $cleanedResourceId -SegmentName 'subscriptions'
内容的提问来源于stack exchange,提问作者learner
相关产品推荐
相关产品推荐

