Search code examples
powershellazure-cli

How to format output from Azure CLI


When I execute

az ad sp list --display-name Shazoo --query "[].appId"

the output is

[
  "2dda03c9-5d9b-4772-a666-c870a8c933c9"
]

which works for copy/paste purposes. However, when I store it in a variable and try to retrieve it, it seems that I'm not obtaining an array (containing a single element) but rather a string (consisting of three lines).

$AppId = az ad sp list --display-name Shazoo --query "[].appId"

If I print $AppId[0] to the console, I see the opening bracket. Printing $AppId[1] produces the GUID but includes the leading spaces and surrounding quotation marks.

Not sure if it's a Azure CLI issue (the output provided) or if it's PowerShell issue (the output rendered).

What would be a good way to research it further?

(I sense it's well-documented but using keywords I'm ignorant of. Hence, I'm not asking how to, rather how to find the actual how-to.)


Solution

  • You're capturing the textual output (i.e. stdout) of the az command line into $AppId.

    Since it's in json format, if you want to be able to work with it as in-memory objects instead you can simply pipe it into ConvertFrom-Json - e.g.

    $stdout = az ad sp list --display-name Shazoo --query "[].appId"
    $AppIds = $stdout | ConvertFrom-Json
    $AppId = $AppIds[0]
    

    (you can simplify these steps into a single pipeline if you prefer - I've left it expanded here for clarity)

    That works with more complex json output as well which might be useful if, for example, you don't use the --query to pre-filter the output, although you might want to also add the --output json parameter onto the call to az to ensure it comes back in the right format...