Powershell – Download file from Azure Storage account container

Posted: September 23, 2022 in Azure, Scripts

This script will check if there are any *.xml files created for current day and if yes, it will download it. Service principal is used for Azure authentication

Creating Service principal

In Azure portal, select Azure Active Directory – App registrations

New registration

Give name and click Register

Click on application – Certificates & secrets – Client secrets – New client secret

Create secret and write it

Click overview and write down application ID and tenant ID

Adding contributor role to Service principal on storage account

On storage account select Access control (IAM) – Add – Add role assignment

Select contributor – Next

Assign access to: User, group or service principal, select service principal

Service principal is used for Azure authentication.ApplicationID, service principal password, subscription and tenant ID are stored in encrypted file.

SSL cert is used for encyption/decryption credentials file.

Create credentials.csv file, example bellow:

appID, appPassword, tenantID, subscriptionID
11-222-3333,secret, 11-224-fggg-sddd,sssss-2222-122222

Encrypt credentials.csv file using one of previous posts, i described procedure in detail so won’t repeat it again.

# Error handling
Function Exception {
     $err = $_.Exception.Message
     write-output $err | timestamp >> $LogFile
     return $err   
 }
 

# Create logs directory and file if not exist
$LogFile = "C:\Navision\Logs\log.txt"
 
If (-not(Test-Path -Path $LogFile)){
    New-Item -Path $LogFile -ItemType File -Force -ErrorAction Stop
}
 
$module = "Az" 
filter timestamp {"$(Get-Date -Format G): $_"}
$resourceGroupName = "myResourceGroup" 
$storageAccName = "myStorageAccount" 
$container_name = "myContainer"
$downloadLocation = "C:\Navision\Downloads"
 
 
# Truncate log file
 
# Get number of lines of log file
$logfileLines = Get-content $LogFile | Measure-Object –Line | select -ExpandProperty Lines
if($logfileLines -gt '5000') {
    (Get-Content $LogFile | Select-Object -Skip 4000) | Out-File $LogFile
  }
 
 
# Create download location if not exists
If (-not(Test-Path -Path $downloadLocation)){
    New-Item -Path $downloadLocation -ItemType Directory -ErrorAction Stop 
}
 
 
Try{
   Write-Output "Decrypting credentials file" | timestamp >> $LogFile
   $CSV_F = Unprotect-CmsMessage -To "*svc-account@example.com*" -Path C:\Navision\credentials.csv.cms -ErrorAction Stop
}
Catch{
    Exception
}
 
 
$Data = $CSV_F | ConvertFrom-Csv
foreach($i in $Data){
   $appID = $i.appID
   $appPassword = $i.appPassword
   $tenantID = $i.tenantID
   $subscriptionID = $i.subscriptionID
}
 
Write-Output "File decrypted" | timestamp >> $LogFile
 
$azureAppCred = (New-Object System.Management.Automation.PSCredential $appID, ( $appPassword | ConvertTo-SecureString -AsPlainText -Force))
 
# Connect to Azure
# Install Az module if not exists
if (-Not (Find-Module -Name $module | Where-Object {$_.Name -eq $module})) {
    Install-Module -Name $module -Force -Verbose | Import-Module
} 
else {
    Write-Host "Module $module exist"
}
 
Write-Output "Connecting to Azure" | timestamp >> $LogFile
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionID -TenantId $tenantID -Credential $azureAppCred -ErrorAction Stop | Out-null
Write-Output "Connection to Azure finished" | timestamp >> $LogFile
 
# Get the storage account
 
Try{
    
   Write-Output "Connecting to storage account $storageAccName and container 
   $container_name " | timestamp >> $LogFile
   $storageAcc = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name 
   $storageAccName -ErrorAction Stop
   ## Get the storage account context 
   $ctx=$storageAcc.Context
   ## Get container and get the xml file(s) created today
   $blobContents = Get-AzStorageBlob -Container $container_name  -Context $ctx -Blob "*.xml" -ErrorAction Stop | Where-Object{$_.LastModified.DateTime -gt ((Get-Date).Date)}
   Write-Output "Successfully connected to  storage account $storageAccName and container $container_name " | timestamp >> $LogFile
}
Catch{
   Exception
}
 
# Download file(s) from Storage account, if file exists
If ($blobContents){
Try{
       ForEach($blobContent in $blobContents){
          $output = "Found file(s) to download:" + $blobContent.Name
          Write-Output $output | timestamp >> $LogFile
          Get-AzStorageBlobContent -Container $container_name  -Context $ctx -Blob 
          $blobContent.Name -Destination $downloadLocation -Force -ErrorAction Stop
          $output = "Successfully downloaded file(s):" + $blobContent.Name
          Write-Output $output | timestamp >> $LogFile
    }
   }
 Catch{
      Exception
 }
}
Else{
  Write-Output "Nothing to download" | timestamp >> $LogFile
}  

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s