Azure Blob Storage:使用 PowerShell 進行檔案複製指南

在這個方便的教程中,學習如何使用 PowerShell 的 Set-AzureStorageBlobContent cmdlet 將文件複製到 Azure Blob Storage。

I’ve been doing a lot of Azure IaaS work via ARM lately in PowerShell. As a result, I’ve unfortunately found out how bad the documentation and behavior is for the Azure PowerShell module but I’ve persisted and have overcome!

作為這個項目的一部分,我不得不上傳一堆文件到 Azure 儲存賬戶容器中。習慣使用 PowerShell 的 Copy-Item cmdlet 來複製文件,我認為 Azure 中應該有類似的東西,可以使用 Azure PowerShell 模組,但我失望了。相反,我面臨的是使用三個單獨的 cmdlet 才能將單個文件上傳到共同的儲存容器。

一旦我弄清楚了如何做,我真的不想每次都記住如何將文件上傳到 Azure 儲存容器。所以,就像任何 PowerShell 開發人員一樣,我製作了一個易於使用的函數叫做 Copy-AzureItem 來將文件複製到 Azure Blob Storage。這個函數為我節省了大量的時間,希望它對你也能有同樣的作用。

這是它的工作原理:

首先,為了將文件放入 Azure ARM 儲存容器中,需要三種不同的“對象”;儲存賬戶、儲存賬戶容器和 Blob 或文件本身。在上傳文件時,必須指定每個這些“對象”。為此,可以在一行上使用三個不同的 cmdlet。

Get-AzStorageAccount @saParams | Get-AzStorageContainer @scParams | Set-AzureStorageBlobContent@bcParams

正如你可以看到的,我正在使用 splatting 將各種參數提供給每個 cmdlet。

這一切只是為了將檔案複製到 Azure 嗎?不用了,謝謝!相反,要不這樣做如何?

Copy-AzureItem -FilePath C:\MyFile.exe -ContainerName azcontainer

簡單多了!雖然我在函數中默認了資源群組和儲存帳戶,但更新起來很容易。

所以,不多說了,請隨意從我的 Github 存儲庫下載此函數。如果你懶得這樣做,也可以從這裡複製貼上。

function Copy-AzureItem
{
	<#
	.SYNOPSIS
		此函數簡化了將檔案上傳到 Azure 儲存帳戶的過程。為了使此函數正常工作,您必須已經使用 Login-AzureAccount 登錄到您的 Azure 訂閱中。上傳的檔案將被稱為儲存 Blob 的檔案名。
		
	.PARAMETER FilePath
		您想要上傳到 Azure 儲存帳戶容器的檔案的本地路徑。
	
	.PARAMETER ContainerName
		將放置檔案的 Azure 儲存帳戶容器的名稱。
	
	.PARAMETER ResourceGroupName
		儲存帳戶所在的資源群組的名稱。
	
	.PARAMETER StorageAccountName
		包含檔案的容器所在的儲存帳戶的名稱。
	#>
	[CmdletBinding()]
	param
	(
		[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
		[ValidateNotNullOrEmpty()]
		[ValidateScript({ Test-Path -Path $_ -PathType Leaf })]
		[Alias('FullName')]
		[string]$FilePath,
	
		[Parameter(Mandatory)]
		[ValidateNotNullOrEmpty()]
		[string]$ContainerName,
	
		[Parameter()]
		[ValidateNotNullOrEmpty()]
		[string]$ResourceGroupName = 'ResourceGroup',
	
		[Parameter()]
		[ValidateNotNullOrEmpty()]
		[string]$StorageAccountName = 'StorageAccount'
	)
	process
	{
		try
		{
			$saParams = @{
				'ResourceGroupName' = $ResourceGroupName
				'Name' = $StorageAccountName
			}
			
			$scParams = @{
				'Container' = $ContainerName
			}
			
			$bcParams = @{
				'File' = $FilePath
				'Blob' = ($FilePath | Split-Path -Leaf)
			}
			Get-AzureRmStorageAccount @saParams | Get-AzureStorageContainer @scParams | Set-AzureStorageBlobContent @bcParams
		}
		catch
		{
			Write-Error $_.Exception.Message
		}
	}
}

Source:
https://adamtheautomator.com/copy-files-to-azure-blob-storage/