Powershell Script to Copy file to Azure Blob


In The previous article we discussed about Automation: Powershell Script  to Create Web App in Microsoft Azure

<#
.SYNOPSIS
Copies file from a local folder to an Azure blob storage container.

.DESCRIPTION
Copies file from a local folder to a named Azure storage blob container. The storage container is assumed to already exist

Note: This script requires an Azure Storage Account to run.

.EXAMPLE
.CopyFiletoAzureContainer.ps1 -AzureSubscriptionName “Visual Studio Enterprise with MSDN” -LocalFilePath C:confdt.BACPAC -StorageAccountName classicstorage9884 -StorageContainer classiccontainer9884
#>

Powershell Script to Copy file from a local folder to an Azure blob storage container

[CmdletBinding(SupportsShouldProcess = $true)]
param(
# The name of valide Azure Subscription associated with Account
[Parameter(Mandatory = $true)]
[string]$AzureSubscriptionName,

# The full path to copy files from.
[Parameter(Mandatory = $true)]
[string]$LocalFilePath,

# The name of the storage account name to copy files to.
[Parameter(Mandatory = $true)]
[string]$StorageAccountName,

# The name of the storage container to copy files to.
[Parameter(Mandatory = $true)]
[string]$StorageContainer
)

# The script has been tested on Powershell 3.0
Set-StrictMode -Version 3

[System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

# To authenticate through Windows Azure Active Directory and downloads associated subscriptions.
#Add-AzureAccount

# To select specific subscription from available subscription “Visual Studio Enterprise with MSDN”
Select-AzureSubscription -SubscriptionName $AzureSubscriptionName

#New-AzureStorageAccount -Location “Central Us” -StorageAccountName classicstorage9884 -Type Standard_LRS

# Ensure the local path given exists. Create it if switch specified to do so.
if (-not (Test-Path $LocalFilePath))
{
throw “Source path ‘$LocalFilePath’ does not exist.  Specify an existing valid path.”
}

# Check if Windows Azure Powershell is avaiable
if ((Get-Module -ListAvailable Azure) -eq $null)
{
throw “Windows Azure Powershell not found! Please install from http://www.windowsazure.com/en-us/downloads/#cmd-line-tools”
}
else
{
Write-Host “Windows Azure Powershell is available!!!”
}

$StorageKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
$StorageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageKey.Primary

try
{
Set-AzureStorageBlobContent -Container $StorageContainer -File $LocalFilePath -Context $StorageContext
Write-Host $LocalFilePath “is uploaded successfully.”
}
catch
{
$warningMessage = “Unable to upload file ” + $LocalFilePath
Write-Warning -Message $warningMessage
}

In the next Article we will discuss about Automation: Powershell Script to Create storage account in Microsoft Azure

Leave a comment

Your email address will not be published. Required fields are marked *