1

I have the following code which gets a collection of the properties of a blob and then uses a foreach loop to locate the selected property value. Is there a bettwer that does not involve looping through the collection in PowerShell 7

$Blobs = Get-AzStorageBlob -Container $containerName -Context $ctx  
ForEach ($Blob in $Blobs){
    if($Blob.Name.IndexOf($blobName) -ge 0)
    {          
        if (Get-Member -InputObject $Blob.ICloudBlob.Properties -Name $blobPropertyName -MemberType Property) {
            $retValue = $Blob.ICloudBlob.Properties.$blobPropertyName
            break;
        }            
    } else{
        Write-Host "Blob not found!"
    }
}
ibexy
  • 609
  • 3
  • 16
  • 34
  • 1
    You could offload the looping to `Where-Object`: `$Blobs |Where-Object {$_.Name -like "*$blobName*"}` - it's not clear why you're dynamically trying to "discover" the properties of the `Properties` object though? – Mathias R. Jessen Sep 08 '20 at 13:30
  • a test needs to check the state of a property on the blob. – ibexy Sep 08 '20 at 15:01
  • Much better/faster/efficient to test for a specific concrete type then, ie, `{$_.Name -like "*$blobName*" -and $_.ICloudBlob -is [Expected.BlobType]}` – Mathias R. Jessen Sep 08 '20 at 15:42

1 Answers1

2

Untested:

(Get-AzStorageBlob -Blob "*$blobName*" -Container $containerName -Context $ctx).
  ICloudBlob.Properties.$blobPropertyName
  • Get-AzStorageBlob's -Blob parameter accepts wildcard expression, so you don't have to manually loop over all blobs to find the one(s) of interest.

  • Note that the command would also work if wildcard "*$blobName*" matched multiple blobs, because PowerShell, since v3, has a feature called member-access enumeration, which is ability to access a member (a property or a method) on a collection and have it implicitly applied to each of its elements, with the results getting collected in an array.

  • As long as Set-StrictMode is off (by default) or set to -Version 1 at the highest, the above will simply return $null if either no matching blob exists or if matching blobs don't have the targeted property.

mklement0
  • 382,024
  • 64
  • 607
  • 775