Search code examples
azurepowershellazure-virtual-network

Unable to loop using az network vnet subnet list from the variable


I have got the code below, however I am unable to loop from the $subnets to get the name and use that within the code. What I am trying to do is delete all the subnets within the virtual network.

$rg = "xxxx"
$vnet = "dddd"
$subnets = az network vnet subnet list --resource-group $rg --vnet-name $vnet
foreach ($subnet in $subnets.name)
{
    write-host $subnet
    az network vnet subnet delete --name $subnet --resource-group $rg --vnet-name $vnet

}

Solution

  • I have modified the code to loop from the $subnets to get the name and use that within the code

    $rg = "<RGName>"
    $vnet = "<vnetName>"
    $subnets = az network vnet subnet list --resource-group $rg --vnet-name $vnet | ConvertFrom-Json
    foreach ($subnet in $subnets)
    {
        write-host $subnet.name
        az network vnet subnet delete --name $subnet.name --resource-group $rg --vnet-name $vnet
    }
    

    When I ran the above code, subnets listed successfully:

    enter image description here

    To confirm that, I checked the same in portal where subnets deleted successfully like below:

    enter image description here