Use dynamic JSON strings with Azure CLI commands in PowerShell

How to create dynamic JSON from an object in PowerShell that works with the Azure CLI when running from the command line.

Philipp Bauknecht
Published in
2 min readAug 2, 2023

--

PowerShell has some interesting quoting issues when running from the command line described here: https://github.com/Azure/azure-cli/blob/dev/doc/quoting-issues-with-powershell.md

I recently came accross an issue when composing a JSON request body for the use with the Azure CLI. So this is my example object defined in PowerShell:

Printing the JSON using Write-Host $customRoleDefinitionJson returns this:

Looks like valid JSON right? Well when trying to use this as a parameter in a Azure CLI command like

it will likely return this error:

So something is wrong with the quotes in the JSON. Applying the workarounds from the 2 provided links in the error message is not enough though as these only work when the JSON string is a single line string!

So to fix this we need to do 2 things:

  • Make the JSON string single line using the -Compress parameter when transforming the object to JSON and
  • Escape the quotes using a Replace function

Doing so the string will look like this:

{\”IsCustom\”:true,\”Name\”:\”test-dev-custom-role\”,\”Actions\”:[\”Microsoft.Resources/deployments/*\”,\”Microsoft.Authorization/*/read\”],\”AssignableScopes\”:[\”/subscriptions/00000000–0000–0000–0000–000000000000/resourceGroups/rg-securengdemo-platform-dev\”]}

Using this single line string with escaped quotes will now work as a parameter in a Azure CLI command.

Hope this will save you some time!

--

--

Philipp Bauknecht

CEO @ medialesson. Microsoft Regional Director & MVP Windows Development. Father of identical twins. Passionate about great User Interfaces, NYC & Steaks