I want to be able to save an object to file, and then have another script pick up that object again and be able to use it.

I run

Export-Clixml -InputObject $object -Encoding UTF8 -Path $file

to save the object to file, but if I run

$object = Import-Clixml $file

I can't manipulate the object as I did before.

Sample code to describe my problem:

#script 1
$objecttofromFile = new-object -com "Microsoft.Update.UpdateColl"
foreach ($herp in $derp) {
    # do stuff, then 
    $null = $objecttofromFile.Add($herp)
}
######## stop, save to file #########
#save shiny UpdateColl object to file
Export-Clixml -InputObject $objecttofromFile -Encoding UTF8 -Path $file

then..

#script 2
$objecttofromFile = Import-Clixml $file
###### start again ######
#assuming object is now a microsoft.update.updatecoll object
$downloader = (new-object -com "Microsoft.Update.Session").CreateUpdateDownloader()
$downloader.Updates = $objecttofromFile #WRONG

Error I'm getting is Exception setting "Updates": "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))", but I'd assume that exporting and importing the object from file could keep the object type as it was.

If I take the code above and throw it into 1 file, removing the stuff between the hashlines, the code renders. But if I save and restore between scripts, it fails.

Am I missing something silly?

link|improve this question

57% accept rate
Have you tried removing the -Encoding parameter from the Export-CliXML cmdlet? – Mathias R. Jessen Dec 29 '11 at 0:51
Same error, unfortunately. – glasnt Dec 29 '11 at 2:00
feedback

1 Answer

up vote 2 down vote accepted

You're not missing anything. export-clixml/import-clixml only exports properties (i.e. no methods), and the imported object has a slightly different type.

Here's some code that illustrates the issue:

$a=dir c:\temp\blogs.html
$a.PSObject.TypeNames
$a | Export-Clixml C:\temp\file.xml

$b=import-clixml c:\temp\file.xml
$b.PSObject.TypeNames

Note that $a is a System.IO.FileInfo, but $b is a Deserialized.System.IO.FileInfo.

link|improve this answer
So is there another method I could use to save and restore an object, since export-clixml doesn't do it nicely? Or do I have to try and re-reserialise the object after importing it? – glasnt Dec 29 '11 at 2:16
You can't "restore" an object this way. You could attempt to use the properties you get back from import-clixml to create a new instance of an object, though (with new-object and probably some object methods). It would depend on what kind of object you had. – Mike Shepard Dec 29 '11 at 2:35
Ah, I thought as much. I should be able to work it out, thanks for your help. Accepting answer. – glasnt Dec 29 '11 at 2:38
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.