使用Set-AzStorageBlobContent仅上载新内容而无提示

我正在枚举本地文件夹并将其上传到Azure存储。我只想将 new 内容上传到我的Azure存储中。如果我将Set-AzStorageBlobContent与-Force一起使用,它将覆盖所有内容。如果我在没有-Force的情况下使用它,则会提示已存在的项目。我可以使用Get-AzStorageBlob检查该项目是否已经存在,但是如果该项目存在,则会显示红色错误。我找不到这些项目的组合,这些项目只能优雅地上传新内容,而不会打印任何错误或提示。我使用了错误的方法吗?

最终编辑:根据Ivan Yang的建议添加工作解决方案。现在,仅上传新文件,而没有任何错误消息。关键是使用-Erroraction Stop将错误消息转换为异常,然后捕获该异常。

# In my code this is part of a Test-Blob function that returns $blobFound
$blobFound = $false
try
{
    $blobInfo = Get-AzStorageBlob `
        -Container $containerName `
        -Context $storageContext `
        -Blob $blobPath `
        -Erroraction Stop

    $blobFound = ($null -ne $blobInfo)
}
catch [microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
{
    # Eat the error that'd otherwise be printed
}

# Note in my code this is actually a call to my Test-Blob function
if ($false -eq $blobFound)
{
    Set-AzStorageBlobContent `
        -Container $containerName `
        -Context $storageContext `
        -File $sourcePath `
        -Blob $blobPath `
        -Force  # -Force is unnecessary but just being paranoid to avoid prompts
}
anxinsimu 回答:使用Set-AzStorageBlobContent仅上载新内容而无提示

我看到您提到尝试Get-AzStorageBlob,为什么不连续使用它呢?

这里的窍门是可以使用try-catch-finally,如果天蓝色的斑点不存在,它可以正确处理错误。

示例代码在我这边可以上传单个文件,您可以对其进行修改以上传多个文件:

$account_name ="xxx"
$account_key ="xxx"      
$context = New-AzStorageContext -StorageAccountName $account_name -StorageAccountKey $account_key    

#use this flag to determine if a blob exists or not in azure. And assume it exists at first.
$is_exist = $true
try
{
 Get-AzStorageBlob -Container test3 -Blob a.txt -Context $context -ErrorAction Stop
}
catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
{
 #if the blob does not exist in azure,do the following
 $is_exist = $false
 Write-Output "the blob DOES NOT exists."
}
finally
{
 #only execute the code when the blob does not exist in azure blob storage.
 if(!$is_exist)
 {
 Set-AzStorageBlobContent -Container test3 -File "d:\myfolder\a.txt" -Blob a.txt -Context $context
 Write-Output "uploaded!"
 }

}
,

这不是PowerShell解决方案,但我建议您看看AzCopy。类似于RoboCopy,但用于Azure存储。命令行工具,可让您同步,复制,移动等等。它是免费的,可在macOS,Linux和Windows上运行。而且,它快速

我使用PowerShell脚本中的AzCopy,它使说谎变得容易得多(我正在管理数百万个文件,AzCopy的稳定性和速度确实有所帮助)

,

此命令不够聪明,无法检测到哪些新文件。您只需要将要上传的文件保留在文件夹中。

,

只需一直使用Set-AzStorageBlobContent -Force。

另一种方法是检查现有文件,下载文件内容,比较文件,然后上传(如果不同)。处理/ IO的数量只会以这种方式增加。

本文链接:https://www.f2er.com/3099858.html

大家都在问