0

I'm using this scrip for Azure monitoring with Zabbix:https://b-blog.info/en/monitoring-azure-resources-with-zabbix.html

If only one SQL database in output:

{"data":{
  "{#SERVERNAME}": "mojsql",
  "{#ID}": "/subscriptions/11111-222222/resourceGroups/rg/providers/Microsoft.Sql/servers/mojsql/databases/mojabaza",
  "{#DATABASENAME}": "mojabaza",
  "{#RGNAME}": "rg"
}
}

If more than one database then output is:

{"data":[
  {
    "{#DATABASENAME}": "mojabaza",
    "{#SERVERNAME}": "mojsql",
    "{#RGNAME}": "rg",
    "{#ID}": "/subscriptions1111-22222/resourceGroups/rg/providers/Microsoft.Sql/servers/mojsql/databases/mojabaza"
  },
  {
    "{#DATABASENAME}": "mojabaza1",
    "{#SERVERNAME}": "mojsql",
    "{#RGNAME}": "rg",
    "{#ID}": "/subscriptions/11111-22222/resourceGroups/rg/providers/Microsoft.Sql/servers/mojsql/databases/mojabaza1"
  }
]
}

Note square brackets are added automatically.

The issue is if only one database in resource group then i must add square brackets in order to see database in zabbix

'{"data":' + '[' + $($result | ConvertTo-Json) + ']' + "`n}";

If more than one database then double square brackets are added and Zabbix shows error.

Is it possible to write a condition if one output then add square brackets something like

if $($results)=1 then

'{"data":' + '[' + $($result | ConvertTo-Json) + ']' + "`n}";

else

'{"data":' + $($result | ConvertTo-Json)  + "`n}";
Milister
  • 648
  • 1
  • 15
  • 33

1 Answers1

3

Your use case is exactly what the PowerShell's array subexpression operator, @(), was designed for:

'{"data":' + (ConvertTo-Json @($result))  + "`n}"

Wrapping a command in @(...) guarantees that its output is an array.

In other words:

  • If the output already is an array (collection), it is, loosely speaking, left alone (technically, a copy of the output array is typically created).

  • If it isn't, it is wrapped in a array, as the that array's only element.

Additionally, in order for ConvertTo-Json to see the array as such, you mustn't use the pipeline and instead pass it as an argument:

Because the pipeline unwraps (unrolls) arguments implicitly, the following two commands are identical:

$result | ...

@($result) | ....  # !! identical
mklement0
  • 382,024
  • 64
  • 607
  • 775