如何使用PowerShell检查Azure blob容器中是否已存在blob

Chr*_*ris 5 powershell azure-powershell

我有一个Windows PowerShell脚本,可以将文件上传到我的Azure Blob存储.我希望文件只在容器中不存在时上传.

如何检查斑点是否已存在?

我厌倦了使用Get-AzureStorageBlob但是如果blob不存在,则会返回错误.我应该解析错误消息以确定blob不存在吗?这似乎不对......

并且Set-AzureStorageBlobContent在blob存在时要求确认.有没有办法自动回答"否"?此cmdlet没有-confirm,-force会覆盖该文件(我不想要).

jim*_*ark 11

这是@Chris的答案的变体.Chris使用Exceptions和Try/Catch.在较大的系统中,try/catch非常棒.它允许代码中的错误引发异常,系统将回溯调用历史记录以查找匹配的catch语句.但是当所有代码都在一个函数中时,为简单起见,我更喜欢检查返回值:

$blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Ignore
if (-not $blob)
{
    Write-Host "Blob Not Found"
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 10

解决方案是在try/catch中包含对Get-AzureStorageBlob的调用,并捕获ResourceNotFoundException以确定blob不存在.

并且不要忘记-ErrorAction Stop最后.

try
{   
    $blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Stop
}
catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
{
    # Add logic here to remember that the blob doesn't exist...
    Write-Host "Blob Not Found"
}
catch
{
    # Report any other error
    Write-Error $Error[0].Exception;
}
Run Code Online (Sandbox Code Playgroud)