Search code examples
jsonpowershellzabbix

Powershell - Remove last comma in foreach


I am rather new to powershell scripting and need help with my script below. I need to remove the last comma "," from the result below. This is JSON format that I need to be able to use this info for Zabbix monitoring of Hyper-V VMs.

script:

    $colItems = Get-VM

write-host "{"
write-host " `"data`":["
write-host

foreach ($objItem in $colItems) {
    $line =  " { `"{#VMNAME}`":`"" + $objItem.Name + "`" , `"{#VMSTATE}`":`"" + $objItem.State + "`" },"
    write-host $line
}

write-host
write-host " ]"
write-host "}"
write-host

Here is the result from this:

{ 
 "data":[

 { "{#VMNAME}":"cp01" , "{#VMSTATE}":"Off" },
 { "{#VMNAME}":"dc01" , "{#VMSTATE}":"Running" },
 { "{#VMNAME}":"ex01" , "{#VMSTATE}":"Off" },
 { "{#VMNAME}":"fc01" , "{#VMSTATE}":"Running" },
 { "{#VMNAME}":"rdg01" , "{#VMSTATE}":"Running" },
 { "{#VMNAME}":"Windows 2012R2 G2 Template" , "{#VMSTATE}":"Off" }, <--- THIS I WANT TO REMOVE

 ]
}

Solution

  • JSON is not a flat string, never try to build it by concatenating flat strings and hoping that it will come out all-right in the end.

    JSON is a serialized data structure, treat it as such. Make a data structure and serialize it.

    In your case that data structure should be an object (i.e. hashtable) that contains the key data, which in turn contains an array of objects. That's easy enough to do.

    $result = @{}
    $result.data = @()
    
    foreach ($vm in Get-VM) {
        $result.data += @{
            "{#VMNAME}" = $vm.Name;
            "{#VMSTATE}" = $vm.State;
        }
    }
    
    $result | ConvertTo-Json
    

    Done.


    Alternative notation, using the foreach shorthand %, saving the temp variables and a few lines:

    @{
        "data" = Get-VM | % { 
            @{
                "{#VMNAME}" = $_.Name;
                "{#VMSTATE}" = $_.State;
            }
        }
    } | ConvertTo-Json