PoshCode Logo PowerShell Code Repository

ConvertTo-CliXml (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/1672"></script>download | new post

Export-CliXml and Import-CliXml only work with files. This is an implementation for sending CliXML directly to the pipeline. Probably needs v2 powershell (not tested in v1).

  1. function ConvertTo-CliXml {
  2.     param(
  3.         [parameter(position=0,mandatory=$true,valuefrompipeline=$true)]
  4.         [validatenotnull()]
  5.         [psobject]$object
  6.     )
  7.     begin {
  8.         $type = [type]::gettype("System.Management.Automation.Serializer")
  9.         $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlwriter]), $null)
  10.         $sw = new-object io.stringwriter
  11.         $xw = new-object xml.xmltextwriter $sw
  12.         $serializer = $ctor.invoke($xw)
  13.         $method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
  14.         $done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance")
  15.     }
  16.     process {
  17.         try {
  18.             $method.invoke($serializer, $object)
  19.         } catch {
  20.             write-warning "Could not serialize $($object.gettype()): $_"
  21.         }
  22.     }
  23.     end {    
  24.         $done.invoke($serializer, @())
  25.         $sw.ToString()
  26.     }
  27. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me