How to Create a Container in an Azure Storage Account using PowerShell

Introduction

In this blog, you will see how to create a container in Azure Storage Account using PowerShell.

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. $storageAccName="azstorageacc1122020"  
  6. $storageContainerName="container001"   
  7.  
  8. ## Connect to Azure Account  
  9. Connect-AzAccount   
  10.  
  11. ## Function to create the storage container  
  12. Function CreateStorageContainer  
  13. {  
  14.     Write-Host -ForegroundColor Green "Creating storage container.."  
  15.     ## Get the storage account in which container has to be created  
  16.     $storageAcc=Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName      
  17.     ## Get the storage account context  
  18.     $ctx=$storageAcc.Context      
  19.  
  20.     ## Check if the storage container exists  
  21.     if(Get-AzStorageContainer -Name $storageContainerName -Context $ctx -ErrorAction SilentlyContinue)  
  22.     {  
  23.         Write-Host -ForegroundColor Magenta $storageContainerName "- container already exists."  
  24.     }  
  25.     else  
  26.     {  
  27.        Write-Host -ForegroundColor Magenta $storageContainerName "- container does not exist."   
  28.        ## Create a new Azure Storage Account  
  29.        New-AzStorageContainer -Name $storageContainerName -Context $ctx -Permission Container  
  30.     }       
  31. }   
  32.   
  33. CreateStorageContainer   
  34.  
  35. ## Disconnect from Azure Account  
  36. Disconnect-AzAccount  

Open the Windows PowerShell window and navigate to the location where the script file was saved.

Run the following command.

.\script.ps1

 

Result:

Container created successfully.

 

Reference

https://docs.microsoft.com/en-us/powershell/module/az.storage/new-azstoragecontainer?view=azps-3.3.0

Summary

In this blog, you saw how to create a container in Azure Storage Account using PowerShell.