Search code examples
azurepowershellazure-virtual-network

How to extract a value from an Azure resource ID using powershell


I have an existing script as per below.

    $subnet_config = Get-AzVirtualNetworkSubnetConfig -Name $subnet.Name -VirtualNetwork $vnet
    $RouteTableJson = $subnet_config.RouteTableText | ConvertFrom-Json
    $RouteJson = $subnet_config.RouteTableText | ConvertFrom-Json
    $rg = [regex]::Match($RouteTableJson.ID, '/resourceGroups/([^/]+)/').Groups[1].Value

The raw json value of ID looks like this.

False /subscriptions/ccccccccccccccc/resourceGroups/rg-mynetwork01/providers/Microsoft.Network/routeTables/my-route

I have tried to use the below to extract the value of routeTables

I would like to extract the routeName but its not working.

$route = [regex]::Match($RouteTableJson.ID, '/routeTables/([^/]+)/').Groups[1].Value

I am curious to find a way to extract any value I require as long as I know what field it relates to, is there a way to do this. So for example I can extract resource group as per the code above, what If I need to extract subscription, In the case of this question routeTables is my issue, I would like to have a consistent way to extract resource values.


Solution

  • Alternatively, you can make use of -split operator to extract a value from an Azure resource ID using PowerShell.

    In my case, I ran below modified PowerShell script and got required values successfully like this:

    $subnet_config = Get-AzVirtualNetworkSubnetConfig -Name $subnet.Name -VirtualNetwork $vnet
    $RouteTableJson = $subnet_config.RouteTableText | ConvertFrom-Json
    
    $rg = ($RouteTableJson.ID -split '/resourceGroups/')[1] -split '/' | Select-Object -First 1
    $subscriptionId = ($RouteTableJson.ID -split '/subscriptions/')[1] -split '/' | Select-Object -First 1
    $routeTableName = ($RouteTableJson.ID -split '/routeTables/')[1] -split '/' | Select-Object -First 1
    

    Response:

    enter image description here