Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell's Import-Clixml from a string

Is there a way to run the Import-Clixml cmdlet on a string or XML object?

It requires a file path as input to produce PowerShell objects and can't get input from an XML object. Since there is the ConvertTo-Xml cmdlet which serializes a PowerShell object into an XML object, why isn't there a convert from XML, which would do the opposite?

I am aware of the System.Xml.Serialization.XmlSerializer class which would do just that. However, I would like to stick with cmdlets to do this.

Is there a way to do this with cmdlets (probably just with Import-Clixml), without creating temporary files?

like image 934
rocku Avatar asked Mar 03 '10 09:03

rocku


People also ask

What is Import Clixml?

The Import-Clixml cmdlet imports a Common Language Infrastructure (CLI) XML file with data that represents Microsoft . NET Framework objects and creates the PowerShell objects. For more information about CLI, see Language independence.

What is Clixml in PowerShell?

The Export-Clixml cmdlet encrypts credential objects by using the Windows Data Protection API. The encryption ensures that only your user account on only that computer can decrypt the contents of the credential object. The exported CLIXML file can't be used on a different computer or by a different user.


1 Answers

I wrote this based on ConvertFrom-CliXml. It seems to work though I didn't test it very thoroughly.

function ConvertFrom-CliXml {
    param(
        [parameter(position=0, mandatory=$true, valuefrompipeline=$true)]
        [validatenotnull()]
        [string]$string
    )
    begin
    {
        $inputstring = ""
    }
    process
    {
        $inputstring += $string
    }
    end
    {
        $type = [type]::gettype("System.Management.Automation.Deserializer")
        $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
        $sr = new-object io.stringreader $inputstring
        $xr = new-object xml.xmltextreader $sr
        $deserializer = $ctor.invoke($xr)
        $method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
        $done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance")
        while (!$done.invoke($deserializer, @()))
        {
            try {
                $method.invoke($deserializer, "")
            } catch {
                write-warning "Could not deserialize object: $_"
            }
        }
    }
}
like image 195
David Sjöstrand Avatar answered Sep 23 '22 16:09

David Sjöstrand