PowerShell script used to Delete resourcegroup level locks in all your Azure Subscriptions

PowerShell script used to Delete resourcegroup level locks in all your Azure Subscriptions

A script used to get the list of all ResourceGroups matching a naming format in all your Azure Subscriptions.

It will check for existence of a ResourceGroup level lock presence and if present, it will delete them.

#Login to the Azure Environment first
Connect-AzAccount

#define the log file path to record all outputs
$Logfile = "$($home)\Downloads\RRE_Athena_NSG\Delete_resourcelock.log"

# Function to write the log entries in the log file. 
function WriteLog
{
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $LogFile -value $LogMessage
}


##get all the subscription which you have access to in the Azure environment.
$azSubs = Get-AzSubscription

#loop through each of the subscription 
foreach ( $azSub in $azSubs ) {
    Set-AzContext -Subscription $azSub | Out-Null
    $azSubName = $azSub.Name

    WriteLog "------------------------------" 
    WriteLog "$($azSubName) being processed" 
    WriteLog "------------------------------" 

    #get all the resourcegorups within the subscription which ends with a -AZSVC
    #$RGS = Get-AzResourceGroup | where ResourceGroupName -Like "*-AZSVC"

    $RGS = Get-AzResourceGroup | where-object {$_.ResourceGroupName -like "*-AZSVC"}

    #loop through each resource group 
    foreach($RG in $RGS) {

        WriteLog  "$($RG.ResourceGroupName) being processed" 

        #get the resourcegroup lock details.
        $lck = Get-AzResourceLock -ResourceGroupName $RG.ResourceGroupName -AtScope
        
        #loop through each lock (just in case there are multiple locks) and perform the deletion of the locks. 
        foreach($lc in $lck) {
            #if the lock does not exist, create one
            if ($null -ne $lc)
            {
               Writelog "$($lc.Name) will be deleted.."

               #Delete the lock and use -Force to delete it.  -WhatIf will show what happens when the command executes.
               #Remove-AzResourceLock -LockId $lc.LockId -Force -WhatIf
               Remove-AzResourceLock -LockId $lc.LockId -Force

               Writelog "$($lc.Name) has been deleted.."
    
            }
            else 
            {
                Writelog "$($RG.ResourceGroupName) does not have a lock"
            }
       }
    }
  }

 

Share via
Copy link