当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何使用 PowerShell 将文件复制到 Azure Blob 存储

作者:精品下载站 日期:2024-12-14 12:40:58 浏览:15 分类:玩电脑

如何使用 PowerShell 将文件复制到 Azure Blob 存储


在此便捷教程中了解如何使用 PowerShell Set-AzureStorageBlobContent cmdlet 将文件复制到 Azure Blob 存储。

我最近在 PowerShell 中通过 ARM 做了很多 Azure IaaS 工作。结果,我不幸地发现 Azure PowerShell 模块的文档和行为有多么糟糕,但我坚持了下来并克服了!

作为该项目的一部分,我必须将一堆文件上传到 Azure 存储帐户容器。习惯使用 PowerShell 的 Copy-Item cmdlet 来复制文件时,我认为 Azure PowerShell 模块中必须有类似 Azure 的功能,但我很失望。相反,我面临着使用三个单独的 cmdlet 来将单个文件存储到公共存储容器中。

一旦我弄清楚如何做到这一点,我就不再想每次都记住如何将文件存储到 Azure 存储容器中。因此,就像任何 PowerShell 开发人员都会做的那样,我创建了一个名为 Copy-AzureItem 的易于使用的函数,用于将文件复制到 Azure Blob 存储。这个功能为我节省了大量的时间,希望它也能为您做同样的事情。

它的工作原理如下:

首先,为了将文件放入 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
		This function simplifies the process of uploading files to an Azure storage account. In order for this function to work you
		must have already logged into your Azure subscription with Login-AzureAccount. The file uploaded will be called the file
		name as the storage blob.
		
	.PARAMETER FilePath
		The local path of the file(s) you'd like to upload to an Azure storage account container.
	
	.PARAMETER ContainerName
		The name of the Azure storage account container the file will be placed in.
	
	.PARAMETER ResourceGroupName
		The name of the resource group the storage account is in.
	
	.PARAMETER StorageAccountName
		The name of the storage account the container that will hold the file is in.
	#>
	[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
		}
	}
}

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯