How to Lock an Azure Storage Account using PowerShell.

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.  
  3. ## Input Parameters  
  4. $resourceGroupName="azpractice"   
  5. $resourceName="azstorageacc1122020"  
  6. $lockName="LockStorageAccount"  
  7. $lockNotes="Cannot delete storage account."  
  8.  
  9. ## Connect to Azure Account  
  10. Connect-AzAccount   
  11.  
  12. ## Function to lock Azure Storage Account resource  
  13. Function LockResource  
  14. {  
  15.     Write-Host -ForegroundColor Green "Locking the resource..."  
  16.  
  17.     ## Lock the resource  
  18.     New-AzResourceLock -LockLevel CanNotDelete -LockName $lockName -LockNotes $lockNotes -ResourceName $resourceName -ResourceType Microsoft.Storage/storageAccounts -ResourceGroupName $resourceGroupName -Force  
  19.   
  20.     Write-Host -ForegroundColor Green "Display all locks for a resource group..."  
  21.  
  22.     ## Display all locks for a resource group  
  23.     Get-AzResourceLock -ResourceGroupName $resourceGroupName  
  24. }  
  25.   
  26. LockResource  
  27.  
  28. ## Disconnect from Azure Account  
  29. 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.