Powershell to dissociate nsg from subnet.

FATOBA, KIMBERLY 45 Reputation points

Hi All:

I am running the Remove-AzNetworkSecurityGroup pwsh command to delete an NSG, this NSG is currently associated with a subnet but there is no direct access over portal to dissociate from the subnet via Azure portal, so the deletion is stuck.

Can anyone kindly provide a quick pwsh one-liner to dissociate NSG from subnet ?

Many Thanks

Azure Virtual Network
Azure Virtual Network
An Azure networking service that is used to provision private networks and optionally to connect to on-premises datacenters.
2,300 questions
{count} votes

Accepted answer
  1. GitaraniSharma-MSFT 49,401 Reputation points Microsoft Employee


    Welcome to Microsoft Q&A Platform. Thank you for reaching out & hope you are doing well.

    I understand that you are running the "Remove-AzNetworkSecurityGroup" PowerShell command to delete an NSG, but this NSG is currently associated with a subnet, and you don't have direct access to Azure portal to dissociate it from the subnet, so the deletion is stuck. You need the PowerShell command to dissociate NSG from subnet.

    You can find the PowerShell commands for dissociating a network security group from a subnet in the below doc:


    Instead of declaring the NSG, you can add $null to the Set-AzVirtualNetworkSubnetConfig command to disassociate the NSG as below:

    ## Place the virtual network configuration into a variable ##
    $vnet = Get-AzVirtualNetwork -Name vnetname -ResourceGroupName rgname
    ## Update the subnet configuration to disassociate the NSG using $null ##
    Set-AzVirtualNetworkSubnetConfig -Name subnetname -VirtualNetwork $vnet -AddressPrefix -NetworkSecurityGroup $null
    ## Update the virtual network ##
    Set-AzVirtualNetwork -VirtualNetwork $vnet

    I tried it in my lab and it works as you can see from the below screenshot:

    enter image description here

    Then you can delete the NSG using the below command:

    Remove-AzNetworkSecurityGroup -Name "nsgname" -ResourceGroupName "rgname"

    Kindly let us know if the above helps or you need further assistance on this issue.

    Please "Accept the answer" if the information helped you. This will help us and others in the community as well.

1 additional answer

Sort by: Most helpful
  1. TP 83,961 Reputation points


    If you navigate to the NSG in the Azure portal, open Subnets blade, you can click on the context menu (three dots) to the right of the subnet and choose Disassociate.

    Please click Accept Answer if the above was helpful.