1

I'm trying to use the zabbix api to get some host id's of hosts by their name. I'm using this example as my starting point.

http://wiki.webperfect.ch/index.php?title=Zabbix_API_-_Create_Maintenance_Window

Here is the example from the zabbix api page (not in powershell) and I can get it to work just fine using postman so I'm assuming the issue is my powershell and not their api.

https://www.zabbix.com/documentation/2.4/manual/api/reference/host/get

Here is my function.

function Get-HostIDs {
param(
    [string]$token,
    [string[]]$hostNames
)

    $params = @{
        body =  @{
            "jsonrpc"= "2.0"
            "method"= "host.get"
            "params"= @{
                "filter"= @{
                    "host"= $hostNames
                }
            }
            "id"= 1
            "auth"= $token
        } | ConvertTo-Json
        uri = "$baseurl/api_jsonrpc.php"
        headers = @{"Content-Type" = "application/json"}
        method = "Post"
    }

    $results = Invoke-WebRequest @params

    return $($results.Content | ConvertFrom-Json).result

}

If I call the function with just 1 hostname like this.

Get-HostIDs -token $authToken -hostNames @('host1')

It works as expected. However when I add the 2nd host like this, it's not working.

Get-HostIDs -token $authToken -hostNames @('host1', 'host2')

When I do some debug write-host statements, it appears that it's coming through as a single string 'host1 host2' instead of as an array.

I feel like I'm missing something really simple, but have been struggling for hours on this. At first I thought their API wasn't documented correctly and you could only send 1 host, but then I tried in post man with their documentation example and it works fine. Thanks for any assistance. Much appreciated.

  • As an aside: Please don't use `@(...)` for array literals - not only is it unnecessary, it is inefficient in PowerShell versions up to 5.0, but, more importantly, it invites conceptual confusion by falsely suggesting that it _constructs_ arrays - see the bottom section of [this answer](https://stackoverflow.com/a/45091504/45375). – mklement0 Mar 19 '20 at 02:34
  • In short: `ConvertTo-Json` unexpectedly limits the serialization depth to 2 levels, requiring you to explicitly pass a sufficient `-Depth` value; see [this answer](https://stackoverflow.com/a/53606883/45375) to the linked post. – mklement0 Mar 19 '20 at 02:38

0 Answers0