当使用Import-CliXml命令重新导入反序列化的对象时,我遇到了Powershell 5类和对象类型的问题。反序列化对象类型问题 - 特别是与Powershell 5类和Import-CliXml
我有型计算机的目标,我希望用来存储以此为XML,然后重新导入这个下一个脚本运行
class Computer
{
$Private:hostname
$Private:ipAddress
Computer([String] $hostname, [String] $ipAddress)
{
$this.hostname = $hostname
$this.ipAddress = $ipAddress
}
static [Computer] reserialize([PSObject] $deserializedComputer)
{
return [Computer]::new($deserializedComputer.hostname, $deserializedComputer.ipAddress)
}
}
时间我导出和导入对象如下:
$computer = [Computer]::new("test-machine", "192.168.1.2")
$computer | Export-CliXml C:\Powershell\exportTest.xml
$deserializedComputer = Import-CliXml C:\Powershell\exportTest.xml
我明白,当这个对象被重新导入,它是反序列化的,基本上只是一个数据容器(类型[Deserialized.Computer])。我试图弄清楚如何在我尝试使用我的reserialize方法对其进行重新串行化之前检查此对象。
例如,如果我试着投$ deserializedComputer它告诉我,:
Cannot convert value "Computer" to type "Computer". Error: "Cannot convert the "Computer" value of type "Deserialized.Computer" to type
"Computer"."
我明白为什么这不能铸造,我只是用错误消息指出对象有知识,它的类型[Deserialized.Computer]
我可以找到从$ deserializedComputer.getMember(),表示它的类型是[Deserialized.Computer]的返回任何内容,我能找到的唯一信息是它的类型[PSObject],我怎样才能确认这个对象的类型确实是[Deserialized.C动态数值]
我应该添加该类型[反序列化。计算机]在运行时不存在,所以我不能直接在我的代码中使用它,否则,我会简单地使用:
$deserializedComputer.getType() -eq [Deserialized.Computer]
'$ deserializedComputer'是'[psobject]'以其'PSTypeNames'叶值设为'Deserialized.Computer'。请参阅'$ deserializedComputer.psobject.TypeNames' –