azure - 通过管道上传带有 Set-AzStorageBlobContent 的 blob 并设置 ContentType 属性
问题描述
使用Az
PowerShell 模块,我试图枚举磁盘上的目录并将输出通过管道传输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
循环调用函数要快得多(在哪里$_
工作)。
解决方案
如果您愿意接受完全不同的解决方案,也可以使用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 类型是从注册表中提取的。可以在标志的帮助下关闭此功能。请参阅标志部分。
推荐阅读
- sql - 在特定持续时间内发生的情节事件
- header - 如何测试 CORS 标头
- c# - 单击链接按钮asp.net c#时,SelectedIndexChanged未在gridview中触发
- asp.net-mvc-5 - 在我的 MVC5 控制器中使用 StructureMap[4.7.0] Setter 注入
- java - 如何将复杂的排序属性指定为 PageRequest 参数?
- javascript - 量角器在出现在页面之前单击元素
- sql - 嵌套 SQL 语句中的错误
- javascript - 将 javascript 字典附加到其他字典
- c# - ADOMD 数据读取器加载时速度很慢
- html - 带参数的 Webpack4 html 部分