Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Remoting Serialization and Deserialization

Are the routines for serializing and deserializing objects from PowerShell (as performed by PowerShell Remoting) available?

I'd like to avoid having to write the objects to disk (with Export-CliXML) and reading it back in with (Import-CliXML).

Basically, I want to get the property bags that the deserialization creates so that I can add them to an AppFabric object cache. Otherwise, AppFabric tries to use .NET serialization, which fails for a number of the standard object types.

Perhaps through the $host or $executioncontext variables?

like image 458
Steven Murawski Avatar asked Apr 11 '11 12:04

Steven Murawski


2 Answers

They have published the PowerShell Remoting Specification which would give you the spec, but the source code they used to implement it is not public at this time. http://msdn.microsoft.com/en-us/library/dd357801(PROT.10).aspx

like image 60
Andy Schneider Avatar answered Nov 03 '22 12:11

Andy Schneider


Oh, I see what you're asking, you're looking for a ConvertTo-CliXml similar to how ConvertTo-Csv works in place of Export-Csv. At first glance it sounds like you're trying to avoid CliXml entirely.

In that case, there's one on PoshCode: ConvertTo-CliXml ConvertFrom-CliXml

Here's a verbatim copy to give you an idea (I haven't checked this for correctness):

function ConvertTo-CliXml {
    param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
        [ValidateNotNullOrEmpty()]
        [PSObject[]]$InputObject
    )
    begin {
        $type = [PSObject].Assembly.GetType('System.Management.Automation.Serializer')
        $ctor = $type.GetConstructor('instance,nonpublic', $null, @([System.Xml.XmlWriter]), $null)
        $sw = New-Object System.IO.StringWriter
        $xw = New-Object System.Xml.XmlTextWriter $sw
        $serializer = $ctor.Invoke($xw)
        $method = $type.GetMethod('Serialize', 'nonpublic,instance', $null, [type[]]@([object]), $null)
        $done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance')
    }
    process {
        try {
            [void]$method.Invoke($serializer, $InputObject)
        } catch {
            Write-Warning "Could not serialize $($InputObject.GetType()): $_"
        }
    }
    end {    
        [void]$done.Invoke($serializer, @())
        $sw.ToString()
        $xw.Close()
        $sw.Dispose()
    }
}
like image 45
Sam Porch Avatar answered Nov 03 '22 12:11

Sam Porch