My brother had the need to convert a bunch of SNMP data into XML for Zabbix. He was trying to do this in Excel but fortunately, he asked me if there was a quicker way to do this rather then struggle with crazy string concatenation formulas. I thought this should be trivial in Powershell and it seems I was right:

Here’s an example of what the input CSV “might” look like (input.csv)

type key delay
4 13.1001 600
5 13 700

And here’s the powershell file (convert.ps1):


function zabbix_template($csv) { 
    write "					

write ""
Import-Csv $csv_file | ForEach-Object { zabbix_template $_ }
write ""

This is obviously not complete but it’s not far from a working solution. To execute this from a windows command line you would do the following:

c:\>powershell .\convert.ps1 input.csv > zabbix.xml

The two main sources of magic are the Import-Csv cmdlet and string interpolation (No need to use string.format for this). The great thing about the Import-Csv cmdlet is that it creates an object for each row using the header of the csv file. Thus the ‘delay’ column in the csv file becomes a ‘delay’ property on an object for each line. This is brilliant because it means I can pass that object to the function that performs the string interpolation and just reference the columns.

I think this is the day I fell in love with Powershell.