用于在 Azure 中列出非托管磁盘的 Foreach 循环

Foreach loop for listing unmanaged disks in Azure

在 PS 中列出 azure 托管磁盘非常容易,但非托管磁盘很难列出,因为它们不是来自 azure POV 的对象。我尝试编写 foreach 循环来列出每个存储帐户的所有未管理磁盘(即 *.vhd 文件)。这是我写的代码:

$StorageAccounts = Get-AzureRmStorageAccount
$sa = $StorageAccounts | foreach-object {

#Get the Management key for the storage account
$key1 = (Get-AzureRmStorageAccountKey -ResourceGroupName $_.ResourceGroupName -name $_.StorageAccountName)[0].value
 
#Get the Storage Context to access the Storage Container
$storageContext = New-AzureStorageContext -StorageAccountName $_.StorageAccountName -StorageAccountKey $key1
 
#Get the Storage Container in the Variable
$storageContainer = Get-AzureStorageContainer -Context $storageContext

$blob = Get-AzureStorageBlob -Container $storageContainer.name -Context $storageContext 

 [PSCustomObject]@{
 "Name" = $blob.Name
 "Length" = $blob.Length
 "Storage Account Name" = $_.StorageAccountName
}
}

我希望循环获取每个存储帐户的所有 vhd,并将其解析为 pscustomobject 以列出所有存储帐户的所有 vhd*,但我收到错误:

Get-AzureStorageBlob : Cannot validate argument on parameter 'Container'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At line:13 char:41

Get-AzureStorageBlob : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Container'. Specified method is not > supported. At line:13 char:41

为什么在第 11 行循环没有将数据解析到 $storageContainer?我可以看到其他两个变量里面有什么,比如 $key1 和 $storageContext。

您可以用这种方式重写您的脚本:

$StorageAccounts = Get-AzureRmStorageAccount
$StorageAccounts.foreach{
    $ctx = $_.Context
    $containers = Get-AzureStorageContainer -Context $ctx
    $containers.foreach{
        $blobs = Get-AzureStorageBlob -Container $_.name -Context $ctx
        $blobs.foreach{
            do_something
        }
    }
}

您不需要获取密钥来构造上下文,因为存储帐户变量包含上下文。然后你需要迭代容器和 blob