首页 > 解决方案 > 通过管道上传带有 Set-AzStorageBlobContent 的 blob 并设置 ContentType 属性

问题描述

使用AzPowerShell 模块,我试图枚举磁盘上的目录并将输出通过管道传输Set-AzStorageBlobContent到 Azure,同时保留文件夹结构。这很好用,除了ContentType所有 blob 的属性都设置为application/octet-stream. 我想根据正在上传的 blob 的文件扩展名动态设置它。

这是基本案例的示例代码:

Get-ChildItem $SourceRoot -Recurse -File |
    Set-AzStorageBlobContent -Container $ContainerName -Context $context -Force

要设置ContentType,我需要添加一个Properties参数,Set-AzStorageBlobContent其值类似于@{ "ContentType" = "<content type>" }。内容类型应根据上传的特定文件扩展名确定。我编写了一个单独的流水线函数,可以将MimeType属性添加到文件对象,但我不知道如何为管道中的参数引用它。例子:

function Add-MimeType{
    [cmdletbinding()]
    param(
        [parameter(
            Mandatory           = $true,
            ValueFromPipeline   = $true)]
        $pipelineInput
    )
    Process {
        $mimeType = Get-MimeType $pipelineInput.Extension
        Add-Member -InputObject $pipelineInput -NotePropertyName "MimeType" -NotePropertyValue $mimeType
        return $pipelineInput
    }
}

function Get-MimeType(
    [string]$FileExtension
)
{
    switch ($FileExtension.ToLowerInvariant())
    {
        '.txt'  { return 'text/plain' }
        '.xml'  { return 'text/xml' }
        default { return 'application/octet-stream' }
    }
}

Get-ChildItem $SourceRoot -Recurse -File |
    Add-MimeType |
        Set-AzStorageBlobContent -Container $ContainerName -Properties @{"ContentType" = "$($_.MimeType)"} -Context $context -Force

在这种情况下似乎$_不可用。还有另一种方法可以做到这一点吗?

我想继续使用流水线的原因是它的工作似乎比使用ForEach-Object循环调用函数要快得多(在哪里$_工作)。

标签: azurepowershellazure-blob-storageazure-powershell

解决方案


如果您愿意接受完全不同的解决方案,也可以使用AzCopy

您可以使用一个命令上传整个文件夹,AzCopy 还可以根据文件扩展名自动猜测正确的 mime 类型。如果这是您设置的一部分,还支持Azure Pipelines 。

命令可能看起来像这样:

# AzCopy v10 will automatically guess the content type unless you pass --no-guess-mime-type
azcopy copy 'C:\myDirectory' 'https://mystorageaccount.blob.core.windows.net/mycontainer' --recursive

# AzCopy V8
azcopy copy 'C:\myDirectory' 'https://mystorageaccount.blob.core.windows.net/mycontainer' /s /SetContentType

取自 的输出AzCopy.exe copy --help

从本地磁盘上传时,AzCopy 会根据文件扩展名或内容(如果未指定扩展名)自动检测文件的内容类型。

内置查找表很小,但在 Unix 上,它会通过本地系统的 mime.types 文件(如果以以下一个或多个名称可用)进行扩充:

  • /etc/mime.types
  • /etc/apache2/mime.types
  • /etc/apache/mime.types

在 Windows 上,MIME 类型是从注册表中提取的。可以在标志的帮助下关闭此功能。请参阅标志部分。


推荐阅读