Introduction

In this blog, you will see how to lock Azure Storage Account resources to prevent unexpected changes (accidentally deleting or modifying resources) using PowerShell.

Lock level can be set as CanNotDelete (Delete in portal) and ReadOnly (Read-only in portal).

CanNotDelete - authorized users can still read and modify a resource, but they can't delete the resource.

ReadOnly - authorized users can read a resource, but they can't delete or update the resource.

Click here to learn more about locking Azure resources.

Prerequisites

Install Azure PowerShell Module to run the script.

PowerShell Script

Open Notepad and paste the following script. Save the file as script.ps1.

  1. ################# Azure Blob Storage - PowerShell ####################
  2. ## Input Parameters
  3. $resourceGroupName="azpractice"
  4. $resourceName="azstorageacc1122020"
  5. $lockName="LockStorageAccount"
  6. $lockNotes="Cannot delete storage account."
  7. ## Connect to Azure Account
  8. Connect-AzAccount
  9. ## Function to lock Azure Storage Account resource
  10. Function LockResource
  11. {
  12. Write-Host -ForegroundColor Green "Locking the resource..."
  13. ## Lock the resource
  14. New-AzResourceLock -LockLevel CanNotDelete -LockName $lockName -LockNotes $lockNotes -ResourceName $resourceName -ResourceType Microsoft.Storage/storageAccounts -ResourceGroupName $resourceGroupName -Force
  15. Write-Host -ForegroundColor Green "Display all locks for a resource group..."
  16. ## Display all locks for a resource group
  17. Get-AzResourceLock -ResourceGroupName $resourceGroupName
  18. }
  19. LockResource
  20. ## Disconnect from Azure Account
  21. Disconnect-AzAccount
Note: Click here to know more about Azure resource providers and types.
Open Windows PowerShell window and navigate to the location where the script file was saved.

Run the following command.

.\script.ps1

Result

Lock added successfully.

When you try to delete the resource, it throws the following error.

Summary

Thus, in this blog, you saw how to lock Azure Storage Account using PowerShell.