PoshCode Archive  Artifact [d4cb68779d]

Artifact d4cb68779d8c55c27ac586a8e969af782f5bddb78e667a96e67b639a9274d3bc:

  • File ConvertFrom-CliXml.ps1 — part of check-in [d13083eab4] at 2018-06-10 13:35:29 on branch trunk — A pair with ConvertTo-CliXml — this version closes and disposes the string reader handle. Now works in PowerShell 3 and later as well. (user: Joel Bennett size: 1654)

# encoding: ascii
# api: powershell
# title: ConvertFrom-CliXml
# description: A pair with ConvertTo-CliXml — this version closes and disposes the string reader handle. Now works in PowerShell 3 and later as well.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: ConvertFrom-CliXml
# x-poshcode-id: 4051
# x-derived-from-id: 4545
# x-archived: 2016-03-20T10:05:58
# x-published: 2016-03-27T14:50:00
#
#
function ConvertFrom-CliXml {
    param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [String[]]$InputObject
    )
    begin
    {
        $OFS = "`n"
        [String]$xmlString = ""
    }
    process
    {
        $xmlString += $InputObject
    }
    end
    {
        $type = [PSObject].Assembly.GetType('System.Management.Automation.Deserializer')
        $ctor = $type.GetConstructor('instance,nonpublic', $null, @([xml.xmlreader]), $null)
        $sr = New-Object System.IO.StringReader $xmlString
        $xr = New-Object System.Xml.XmlTextReader $sr
        $deserializer = $ctor.Invoke($xr)
        $method = @($type.GetMethods('nonpublic,instance') | Where-Object {$_.Name -like "Deserialize"})[1]
        $done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance')
        while (!$done.Invoke($deserializer, @()))
        {
            try {
                $method.Invoke($deserializer, "")
            } catch {
                Write-Warning "Could not deserialize ${string}: $_"
            }
        }
        $xr.Close()
        $sr.Dispose()
    }
}