0

I have a PowerShell script to run an Azure CLI command:

Param (
    [parameter(Mandatory = $false)]
    [string] $ruleName = "Trusted Device1"
)

az webapp config access-restriction add -g "my-rg" -n "my-app" --rule-name $ruleName --action Allow --ip-address "10.10.10.0/24" --priority 10;

It returns "Bad Request" because $ruleName contains space.

If I run the Azure CLI command directly from PowerShell command window with quoted string, it will work.

az webapp config access-restriction add -g "my-rg" -n "my-app" --rule-name "Trusted device1" --action Allow --ip-address "10.10.10.0/24" --priority 10;

So how do I quote string parameter containing spaces and pass it to Azure CLI command inside a PowerShell script?

Using the following in the script doesn't work

az webapp config access-restriction add -g "my-rg" -n "my-app" --rule-name "$ruleName" --action Allow --ip-address "10.10.10.0/24" --priority 10;
user3616544
  • 1,023
  • 1
  • 9
  • 31
  • 1
    PowerShell automatically double-quotes variable values with spaces behind the scenes; try `$v='a b'; cmd /c echo $v`, for instance. (Conversely, even if you explicitly double-quote a value (`"$ruleName"`), PowerShell will pass the value _unquoted_ if it does _not_ contains spaces.) The commands posted in your question do not explain your symptom. – mklement0 Jun 20 '21 at 17:19

1 Answers1

1

Not sure which environment or PowerShell version you are encountering this with, but I was able to run this successfully on PowerShell 7.1 and 5.1 as well. With PS, wrapping the argument in quotation marks should suffice when passing an argument containing whitespace as follows:

.\CreateAccessRestriction.ps1 -ruleName "My Rule"

Also, to be sure of how the passed parameters are being interpreted, it should help to include --debug with the az cli command to test. This would print a debug log statement like:

DEBUG: cli.knack.cli: Command arguments: ['webapp', 'config', 'access-restriction', 'add', '-g', 'myRG', '-n', 'myApp', '--rule-name', 'My Rule', '--action', 'Allow', 
'--ip-address', '10.10.10.0/24', '--priority', '10', '--debug']

As mentioned in the Azure CLI docs, when working with Azure CLI commands, be aware of how your shell uses quotation marks and escapes characters. Due to a known issue in PowerShell, some extra escaping rules apply. This is described in detail in this article: Quoting issues with PowerShell.

Bhargavi Annadevara
  • 4,923
  • 2
  • 13
  • 30