Skip to content

Instantly share code, notes, and snippets.

@cchurch
Created October 22, 2014 22:52
Show Gist options
  • Save cchurch/2a29eb4421bd621f0713 to your computer and use it in GitHub Desktop.
Save cchurch/2a29eb4421bd621f0713 to your computer and use it in GitHub Desktop.
Convert basic Python objects to PowerShell CLIXML format
def clixml(a, top=True):
import xml.etree.ElementTree as ET
if top:
objects = ET.Element('Objects')
obj = clixml(a, top=False)
obj.tag = 'Object'
objects.append(obj)
return ET.tostring(objects)
elif a is None:
return ET.Element('Property')
elif a in (True, False):
return ET.Element('Property', Type='System.Boolean', text=str(a))
elif isinstance(a, int):
return ET.Element('Property', Type='System.Int32', text=str(a))
elif isinstance(a, float):
return ET.Element('Property', Type='System.Double', text=str(a))
elif isinstance(a, basestring):
return ET.Element('Property', Type='System.String', text=str(a))
elif isinstance(a, list):
obj = ET.Element('Property', Type='System.Object[]')
[obj.append(clixml(i, top=False)) for i in a]
return obj
elif isinstance(a, dict):
obj = ET.Element('Property', Type='System.Collections.Hashtable')
for k,v in a.items():
kobj = clixml(k, top=False)
kobj.set('Name', 'Key')
obj.append(kobj)
vobj = clixml(v, top=False)
vobj.set('Name', 'Value')
obj.append(vobj)
return obj
else:
raise NotImplementedError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment