Search code examples
azurepowershellloopsforeachdisk

Foreach loop for listing unmanaged disks in Azure


It's very easy to list azure managed disks in PS, but unmanaged ones are very tricky to list, as they're not objects from azure POV. I tried to wrote foreach loop to list me all unamanged disks (i.e. *.vhd files) for each storage account. This is the code I wrote:

$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
}
}

I want the loop to fetch all the vhd's for each storageaccount and parse it into pscustomobject to list me all vhd*s from all storage accounts, but I get an error:

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

Why loop is not parsing data to $storageContainer in line 11? I can see what's inside other two vars like $key1 and $storageContext.


Solution

  • you can rewrite your script in this fashion:

    $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
            }
        }
    }
    

    you dont need to get keys to construct context, because storage account variable contains the context. and then you need to iterate containers and blobs