Created
May 13, 2020 14:14
-
-
Save brianvanderlugt/d25e10a4baa7e825735ac5a14d54a963 to your computer and use it in GitHub Desktop.
PowerShell Az Blob Container Copy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Modules Az | |
param( | |
[Parameter(Mandatory)] | |
[String]$StorageAccountName, | |
[Parameter(Mandatory)] | |
[String]$ContainerName, | |
[Parameter(Mandatory = $false)] | |
[String]$BlobFilter, | |
[Parameter(Mandatory,ParameterSetName='ByAccountName')] | |
[String]$DestStorageAccountName, | |
[Parameter(Mandatory,ParameterSetName='DestinationByLocal')] | |
[Switch]$DestLocal | |
) | |
BEGIN { | |
$tmpFolder = Join-Path -Path $env:TEMP -ChildPath $(New-Guid) | |
Write-Output "$(Get-Date): Creating temp directory: '$tmpFolder'" | |
New-Item -Path $tmpFolder -ItemType Directory | Out-Null | |
$srcContext = New-AzStorageContext -StorageAccountName $StorageAccountName -UseConnectedAccount | |
switch($PSCmdlet.ParameterSetName){ | |
'ByAccountName'{ | |
$destContext = New-AzStorageContext -StorageAccountName $DestStorageAccountName -UseConnectedAccount | |
} | |
'DestinationByLocal'{ | |
$destContext = New-AzStorageContext -Local | |
} | |
} | |
} | |
PROCESS { | |
try { | |
$srcParams = @{ | |
Context = $srcContext | |
Container = $ContainerName | |
} | |
if (-not([String]::IsNullOrEmpty($BlobFilter))){ | |
$srcParams.Add('Blob', $BlobFilter) | |
} | |
Get-AzStorageBlob @srcParams | | |
foreach { Get-AzStorageBlobContent -Context $srcContext -Container $ContainerName -Destination $tmpFolder -Blob $_.Name } | |
if ($null -eq (Get-AzStorageContainer -Context $destContext -Name $ContainerName -ea 0)){ | |
Write-Output "$(Get-Date): Creating destination container: '$ContainerName'" | |
New-AzStorageContainer -Context $destContext -Container $ContainerName | |
} | |
Get-ChildItem -Path $tmpFolder | | |
foreach { Set-AzStorageBlobContent -Container $ContainerName -File $_ -Context $destContext -Blob $($_.Name) } | |
} | |
finally { | |
Write-Output "$(Get-Date): Cleaning up temp directory: '$tmpFolder'" | |
Remove-Item -Path $tmpFolder -Recurse | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment