PowerShell检查Azure存储容器是否存在

n6lpvg4x  于 2023-05-23  发布在  Shell
关注(0)|答案(4)|浏览(184)

我正在创建一个PowerShell脚本来执行几个步骤,其中一个涉及Azure存储容器删除:

  1. Remove-AzureStorageContainer ....

下一步取决于该移除是否完成。
我如何知道上一个REMOVE已成功执行,以便继续执行下一步?
类似的东西;

  1. while(Test-AzureStorageContainerExist "mycontainer")
  2. {
  3. Start-Sleep -s 100
  4. }
  5. <step2>

不幸的是,“Test-AzureStorageContainerExist”似乎不可用。:)

cedebl8k

cedebl8k1#

您可以请求存储容器的列表并查找特定的一个,然后等待,直到它不再返回为止。如果帐户中没有大量的容器,则可以正常工作。如果它确实有很多容器,那么这根本不会有效率。

  1. while (Get-AzureStorageContainer | Where-Object { $_.Name -eq "mycontainer" })
  2. {
  3. Start-Sleep -s 100
  4. "Still there..."
  5. }

Get-AzureStorageContainercmdlet还接受一个-Name参数,您可以执行一个循环,要求返回该参数;然而,当容器不存在时,它会抛出一个错误(Resource not found),而不是提供一个空结果,因此您可以捕获该错误并知道它已经消失了(确保显式地查找Reource Not found vs a timeout或类似的东西)。
更新:另一种选择是直接调用REST API来获取容器属性,直到得到404(未找到)。这意味着集装箱不见了。http://msdn.microsoft.com/en-us/library/dd179370.aspx

r6vfmomb

r6vfmomb2#

try/catch方法:

  1. try {
  2. while($true){
  3. Get-AzureStorageContainer -Name "myContainer -ErrorAction stop
  4. sleep -s 100
  5. }
  6. }
  7. catch {
  8. write-host "no such container"
  9. # step 2 action
  10. }
r7knjye2

r7knjye23#

这个管用

  1. $containerDeleted = $false
  2. while(!$containerDeleted) {
  3. Try {
  4. Write-Host "Try::New-AzureStorageContainer"
  5. New-AzureStorageContainer -Name $storageContainerName -Permission Off -Context $context -Verbose -ErrorAction Stop
  6. $containerDeleted = $true
  7. } catch [Microsoft.WindowsAzure.Storage.StorageException] {
  8. Start-Sleep -s 5
  9. }
  10. }

如果您查看返回的错误消息(异常代码),则是正在删除的容器

rqmkfv5c

rqmkfv5c4#

如果你是因为标题而不是OP的问题(这是谷歌的第一次点击),试试这个:

  1. # crate a context of the storage account.
  2. # this binds the following commands to a certain storage account.
  3. $context = New-AzStorageContext -StorageAccountName $AccountName
  4. # check whether the container exists.
  5. Get-AzStorageContainer -Context $context -Name $containerName
  6. # check the return value of the last call.
  7. if ($? -eq $false) {
  8. # do what you need to do when it does not exist.
  9. } else {
  10. # do what you need to do when it does exist.
  11. }

至少对我来说,捕获异常并不起作用,但这确实起作用了。

相关问题