Home > Mobile >  Can I Iterate from JSON array in PowerShell?
Can I Iterate from JSON array in PowerShell?

Time:09-17

I'm using Azure Pipelines to make some automations, and in one job I wish to iterate from a JSON to config WebApp settings. I'm using powershell, but I'm struggling to do something like this, made in Python:

import json

varJson = json.loads('''{
        "key1": "value1", 
        "key2": "value2", 
        "key3": "value3",
        "key4": "value4"
    }''')

for i in varJson:
    print(f'az webapp config appsettings set -g resourceGroup -n appName --settings {i}=\"{varJson[i]}\"')

The output I wish is something like:

az webapp config appsettings set -g resourceGroup -n appName --settings key1="value1"
...

I tried to use objects, but it's confuse to me:

$Json = @'
{
    "key1": "value1", 
    "key2": "value2", 
    "key3": "value3",
    "key4": "value4"
}
'@ | ConvertFrom-Json
ForEach-Object -InputObject $Json {
    Write-Host $_.PSObject.Properties.Name 
}
Write-Host $Json

Can I do something in PowerShell similar of what I did in python? Or there's an easier way?

CodePudding user response:

Try the following:

$fromJson = @'
{
    "key1": "value1", 
    "key2": "value2", 
    "key3": "value3",
    "key4": "value4"
}
'@ | ConvertFrom-Json

foreach ($prop in $fromJson.psobject.Properties) {
  @"
    az webapp config appsettings set -g resourceGroup -n appName --settings "$($prop.Name)=$($prop.Value)"
"@
}

Note:

  • .psobject is an intrinsic member that PowerShell makes available on objects of any type, and it is a rich source of reflection; its .Properties property returns a collection of objects describing the properties of the object at hand, each of which have a .Name and .Value property.

  • As in your Python code, the az command line is merely printed as a string, not invoked.

    • To perform the actual invocations, remove the @" and "@ lines (the construct as a whole is a PowerShell here-string).
  • "$($prop.Name)=$($prop.Value)" results in something like "key1=value1", which PowerShell would pass without quoting to az; only if the value part contained spaces would PowerShell double-quote the - entire - argument.

    • If az requires partial quoting on its command line, such as key1="value 1", the easiest solution is to call via cmd.exe /c:

      cmd /c "az webapp config appsettings set -g resourceGroup -n appName --settings $($prop.Name)=`"$($prop.Value)`""
      
    • If you want to be shielded from such intricacies, consider installing the Native module (Install-Module Native), whose ie function automatically performs the partial quoting for you (if the value part contains spaces), among other features, so that you can focus on PowerShell's syntax alone:

      ie az webapp config appsettings set -g resourceGroup -n appName --settings "$($prop.Name)=$($prop.Value)"
      
  • Related