Goa
Goa

Reputation: 87

Trouble exporting and importing custom type objects using xml

Trouble exporting and importing custom type objects using XML. The objects change type and lose methods.

Script:

# Powershell 5

$file = 'C:\Scripts\Storage\file.xml'

class test {
    [string] $name
    [string] getValue() {
        return 'value'
    }
}

$a = [test]::new()
$a.GetType()  # object type is "test"
$a |gm        # it has method "getValue" | Name       : getValue , 
MemberType : Method


$a | Export-Clixml $file
$b = Import-Clixml $file


$b.GetType()  # object type is "PSObject"
$b | gm       #  method "getValue" is no longer there

How do I get $b.gettype() -eq $a.gettype() to be true?

I want to export the object to XML and re-import it, without losing its type and methods.

Upvotes: 4

Views: 505

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36332

So this is where things get a little confusing. Yes, $b is a PSObject, but it is also an object with type [test] as well. To see this you can do:

$b.psobject.TypeNames

You will see:

Deserialized.test
Deserialized.System.Object

You do lose the method though, due to the object being deserialized. This is inherent to exporting to XML, and then re-importing it. Deserialization is a necessary evil when saving objects to disk, as when you import them later they are no longer 'live' objects, they're just a snapshot of what the objects looked like when you exported them to disk.

The exported objects maintain all of their properties, just as you would expect a snapshot of your friend to, (the color of their hair, the smirk on their face, the vulgar hand gesture they're giving a stuffed kangaroo), but they lose the interactive methods (the photo will not giggle no matter how much you tickle it).

What you can do, if you really want $b to have its methods, is to strongly type it when you import it, such as:

[test]$b = Import-Clixml $file

At this point $b will behave exactly how $a does.

Upvotes: 5

Related Questions