Search code examples
powershellazure-clijmespath

How to detect if a resource exists using list option and JMESPath (az-cli)?


I am trying to detech if a given query returns any results and branch based on that. I'm using PowerShell and this works

(az network vnet list --query "[?name=='testvnet']" | ConvertFrom-Json).Length

but then I was wondering if this would be possible with JMESPath and tried variations of

az network vnet list --query "length([?name=='testvnet'])"

but it appears this is not possible using JMESPath. Or is there a way?

According to the documentation at https://jmespath.readthedocs.io/en/stable/specification.html#length there is a function called length and I understand it work like that.

The error for this particular example is

az : az network vnet list: error: argument --query: invalid jmespath_type value: "length([?name=='testvnet']"
At line:1 char:1
+ az network vnet list --query "length([?name=='testvnet'])"

The missing end parenthesis in the error message is suspicious. This may be due to using az cli in a PowerShell console.


Solution

  • You're almost there. Try

    az network vnet list --query "[?name == 'testvnet'] | length(@)"