我想能够保存一个对象到文件,然后让另一个脚本再次拿起这个对象,并能够使用它。
我跑
Export-Clixml -InputObject $object -Encoding UTF8 -Path $file
将对象保存到文件,但如果我运行
$object = Import-Clixml $file
我不能像以前那样操纵对象。
示例代码来描述我的问题:
#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
然后..
#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
我得到的错误是Exception setting "Updates": "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))" ,但我假设从文件中导出和导入对象可以保持对象types。
如果我把上面的代码放到1个文件中,删除哈希函数之间的东西,代码会呈现出来。 但是,如果我保存和恢复脚本之间,它会失败。
我错过了一些愚蠢的东西吗?
你不会错过任何东西。 export-clixml / import-clixml只导出属性(即没有方法),导入的对象有一个稍微不同的types。
以下是一些说明问题的代码:
$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
请注意$ a是一个System.IO.FileInfo,但$ b是一个Deserialized.System.IO.FileInfo。