Search code examples
azurepowershellazure-resource-managerazure-powershellpowershell-7

Powershell 7: Issue with Where-Object and tags


I am running a simple powershell query in Azure. I am looking to filter only the Web Apps with a certain Tag assigned to it:

$apps = Get-AzWebApp | Where-Object {$_.Tags["Application"] -match "any-tag-value"} 

if ($apps) {
    foreach ($app in $apps) {
        Write-Host $app.Name
    }
}

Regardless, if it finds anything or not, the first two results are always InvalidOperation: Cannot index into a null array.. After that it lists what it finds.

If I remove the Where-Object clause everything works fine.

I am not sure why this error occurs and what are these two empty arrays that go into the resultset.

Anyone can shed light into this?


Solution

  • Most likely the first 2 resources listed by your cmdlet don't have a tag set and referencing a property that is not set will be null and then indexing a null value causes the exception you're seeing:

    ([pscustomobject]@{ }).PropertyDoesNotExist['foo']
    
    # Throws: InvalidOperation: Cannot index into a null array.
    

    The easiest workaround for this can be via dot notation and let member-access enumeration handle the indexing for you, that way:

    $apps = Get-AzWebApp | Where-Object { $_.Tags.Application -match "any-tag-value" }
    

    Or, you can first check if such property exist and then try to index it:

    $apps = Get-AzWebApp | Where-Object { $_.Tags -and $_.Tags['Application'] -match "any-tag-value" }