2

当使用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] 
+1

'$ deserializedComputer'是'[psobject]'以其'PSTypeNames'叶值设为'Deserialized.Computer'。请参阅'$ deserializedComputer.psobject.TypeNames' –

回答

2

使用(提示:GM是别名获取会员)

$type = $deserializedComputer | gm | Select -Property TypeName -First 1 

,那么你应该能够访问类的值

$type.TypeName 

您也可以键入检查,以确保它是一台电脑使用

$deserializedComputer.ToString() 

或者,如果你希望其他方式使用

[type]$deserializedComputer.ToString() 

编辑:

您可以通过以下

# you can also use $deserializedComputer.ToString() -eq [Computer].ToString() 
if ([type]$deserializedComputer.ToString() -eq [Computer]) 
{ 

} 

你满级将类似于检查:

class Computer 
{ 
    $Private:hostname 
    $Private:ipAddress 

    Computer(){} 

    Computer([String] $hostname, [String] $ipAddress) 
    { 
     $this.hostname = $hostname 
     $this.ipAddress = $ipAddress 
    } 
    static [Computer] reserialize([PSObject] $deserializedComputer) 
    { 
    # you can also use $deserializedComputer.ToString() -eq [Computer].ToString() 
    if ([type]$deserializedComputer.ToString() -eq [Computer]) 
    { 
     return [Computer]::new($deserializedComputer.hostname, $deserializedComputer.ipAddress) 
    } 
    return [Computer]::new() 
    } 
} 

和导出/导入

$filePath = "C:\Powershell\exportTest.xml" 

$computer = [Computer]::new("test-machine", "192.168.1.2") 
$computer | Export-CliXml $filePath 
$deserializedComputer = Import-CliXml $filePath 

而重新序列化方法

[Computer]::reserialize($deserializedComputer) 
相关问题