How to: File synchronization between two different Azure File Share using PowerShell Custom code

Business requirement:

Business needs two storages in different Azure cloud regions that should sync files between them without cost to company and inline to security requirement. Both storages will be accessed from on-premise server.

pre-requisites:

  1. Azure subscription access
  2. Administrator privilege to run PowerShell or PowerShell ISE on remote server or Desktop
  3. Set-Executionpolicy to remotesigned or unrestricted in PowerShell environment

Solution:

Step 01: Login to your subscription and create two resource groups in two different regions using Azure portal or PowerShell. Below PowerShell lines create them for you.

New-AzResourceGroup -Name ‘EastUS2-RG’ -Location ‘EastUS2’

New-AzResourceGroup -Name ‘WestUS2-RG’ -Location ‘WestUS2’

Step 02: Create two storage accounts in above resource groups using Azure portal or PowerShell. Below PowerShell lines create them for you.

New-AzStorageAccount -ResourceGroupName ‘EastUS2-RG’ -Name ‘eastus2storage’ -Location ‘East US 2’ -SkuName Standard_LRS -Kind StorageV2

New-AzStorageAccount -ResourceGroupName ‘WestUS2-RG’ -Name ‘westus2storage’ -Location ‘WestUS2’ -SkuName Standard_LRS -Kind StorageV2

You need to select the SKU’s as per your organization standards. From my self-account pricing view I select above ones.

Step 03: Create file share as per your requirement with Azure standards, copy the connect code snippet to connect from on-premise. This code should be confidential as it contains the storage key which can be misused by anyone.

Step 04: Logon to your server or desktop from where you have to perform synchronization activity, run the code snippet copied as instructed in step 03. Drives will be created for you on windows machine.

Step 05: Execute the below PowerShell snippet to synchronize the data between folders.

$DownloadFolder = ‘y:\<fileshare01>\’

$KeepFolder = ‘z:\<fileshare02>’

$DownloadFiles = Get-ChildItem -Path $DownloadFolder

$KeepFiles = Get-ChildItem -Path $KeepFolder

$FileDiffs = Compare-Object -ReferenceObject $DownloadFiles -DifferenceObject $KeepFiles

$FileDiffs | foreach {

$copyParams = @{

‘Path’ = $_.InputObject.Fullname

}

$Downloadll = $copyParams.path

if ($_.SideIndicator -eq ‘=>’)

{

Copy-Item $Downloadll -Destination $KeepFolder

}}

Now if the above code is scheduled as a job, it will automatically synchronize files and folders between two Azure cloud storages. This scenario helps you even in development environment to copy files from one location to other.

Above code will copy only files and folders that are changed.