Q: How can I use PowerShell to obtain the storage key for my Azure storage account?

A: A key is required to access storage accounts in Azure. The key is typically obtained through the Azure portals, and there's a primary and secondary key. Having to fetch the key from the portal before use in a script is cumbersome and not very secure. You certainly don't want keys stored in change control libraries with your script. One option is to use PowerShell to fetch the storage key; however, this method requires credentials to use the Azure subscription. If this is an option, run the following code to fetch the key and save it into a variable to use to connect to a storage account.

#Create a variable to store the Storage Account name
$StorageAccount = 'savtechstoreeastus'

#Save the storage account key
$StorageKey = (Get-AzureStorageKey `
-StorageAccountName $StorageAccount).Primary

#Create a context to the storage account
$storageaccount1 = new-azurestoragecontext `
-storageaccountname $StorageAccount -storageaccountkey $StorageKey