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):

param($csv_file)
 
function zabbix_template($csv) { 
    write "	<item type=""$($csv.type)"" key=""$($csv.key)"" value_type=""1"">				
        <description>13.1001</description>				
        <delay>$($csv.delay)</delay>				
        <history>30</history>				
        <trends>365</trends>				
        <snmp_community>public</snmp_community>				
        <snmp_oid>.1.3.6.1.2.1.47.1.1.1.1.13.1001</snmp_oid>				
        <snmp_port>161</snmp_port>				
        <applications>				
            <application>General</application>
        </applications>
    </item>"
}
 
write "<items>"
Import-Csv $csv_file | ForEach-Object { zabbix_template $_ }
write "</items>"

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.