How to Retrieve and Refresh Azure Storage Account Access Keys using PowerShell

Introduction 

In this blog, you will see how to retrieve and refresh Azure Storage Account Access Keys using PowerShell.
 
Prerequisites
 
Install Azure PowerShell Module to run the script.
 
PowerShell Script
 
Open Notepad and paste the below code. Save the file as script.ps1.
  1. ################# Azure Blob Storage - PowerShell ####################  
  2.  
  3. ## Input Parameters  
  4. $resourceGroupName="azpractice"   
  5. $storageAccountName="azstorageacc1122020"  
  6.  
  7. ## Connect to Azure Account  
  8. Connect-AzAccount   
  9.  
  10. ## Function to retrive and refresh access keys  
  11. Function RetriveRefreshKeys  
  12. {  
  13.     Write-Host -ForegroundColor Green "Retrieving the storage accounts keys..."  
  14.  
  15.     ## Get the storage account keys  
  16.     $storageAccColl=Get-AzStorageAccount  
  17.     $storageAccountKey1 = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0]  
  18.     $storageAccountKey2= (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[1]  
  19.   
  20.     Write-Host -ForegroundColor Yellow "Storage Account Key 1: " $storageAccountKey1  
  21.     Write-Host -ForegroundColor Yellow "Storage Account Key 2: " $storageAccountKey2  
  22.   
  23.     Write-Host -ForegroundColor Green "Refreshing the storage accounts key (2)..."  
  24.  
  25.     ## Refresh the storage account key 2  
  26.     New-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName -KeyName key2  
  27.  
  28.     ## Retrive storage account key 2  
  29.     $storageAccountKey2= (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[1]  
  30.     Write-Host -ForegroundColor Yellow "Storage Account Key 2: " $storageAccountKey2          
  31. }  
  32.   
  33. RetriveRefreshKeys  
  34.  
  35. ## Disconnect from Azure Account  
  36. Disconnect-AzAccount   
  
Open PowerShell window and navigate to the location where the script file was saved. Run the following command.
 
./script.ps1
 
Result
 
 
 
 
Summary
 
Thus, in this blog, you saw how to retrieve and refresh Azure Storage Account Access Keys using PowerShell.