How to Export Azure Resource Group Locks using PowerShell

Locks play a pivotal role in the management of Azure resources, particularly in Production environments. However, when the need arises for a swift assessment of lock status, perhaps for auditing purposes or to facilitate scheduled actions, efficiency becomes paramount

Well that’s where the short PowerShell script below comes into play. It will open a Browser session to authenticate as a given user and then query the given Subscription, reporting on whether each Resource Group in the Subscription has an applied Lock.

The script isn’t designed to handle massive quantities of Resource Groups and there are numerous improvements that could be made quickly but hopefully this can act as a starting point for others.

The Script

Connect-AzAccount

$subscriptionName = "Subscription Name"
Get-AzSubscription -SubscriptionName $subscriptionName -WarningAction SilentlyContinue | Set-AZContext -WarningAction SilentlyContinue
    
try {
    # Get all resource groups, excluding some managed groups
    $ResourceGroups = Get-AzResourceGroup -ErrorAction stop | where-object {$_.ResourceGroupName -inotlike "MC_*"}
} catch {
    Write-Warning "Failed on get Resource Groups"
    continue
}

$ReportObjects = @()
$count = 1
$ResourceGroups | foreach-object {
    Write-Host "Processing $count of $($ResourceGroups.Count)"
    $lock = Get-AzResourceLock -ResourceGroupName $_.ResourceGroupName -AtScope
    
    $ReportObjects += [pscustomobject]@{
        'Name' = $_.ResourceGroupName;
        'Owner' = $_.Tags.Owner;
        Criticality = $_.Tags.Criticality;
        Func = $_.Tags.Function;
        Locks = if($lock) {$true} else {$false};
    }

    $count++
}
    
$date = Get-Date
$ReportObjects | export-csv -NoClobber -NoTypeInformation "C:\temp\report-$($date.Year)$($date.Month)$($date.Day)$($date.Millisecond).csv"
Invoke-Item "C:\temp\report-$($date.Year)$($date.Month)$($date.Day)$($date.Millisecond).csv"

Write-Host -ForegroundColor green "Finished Reporting"

Disconnect-AzAccount

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.