Export and import problem objects using xml

Export and import custom type objects using XML. 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()like the truth?

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

+4
source share
1 answer

Thus, here everything becomes a bit confusing. Yes, it $bis a PSObject, but it is also an object of type [test]. To see this, you can:

$b.psobject.TypeNames

You will see:

Deserialized.test
Deserialized.System.Object

, - . XML, . Deserialization , "" , , , .

, , ( , , , ), ( , ).

, , $b , , :

[test]$b = Import-Clixml $file

$b , $a.

+5

Source: https://habr.com/ru/post/1682432/


All Articles