使用 Import-CliXml 命令重新导入反序列化对象时,我遇到了 Powershell 5 类和对象类型的问题。
我有一个 Computer 类型的对象,我希望将其存储为 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)
}
}
Run Code Online (Sandbox Code Playgroud)
我使用以下方法导出和导入对象:
$computer = [Computer]::new("test-machine", "192.168.1.2")
$computer | Export-CliXml C:\Powershell\exportTest.xml
$deserializedComputer = Import-CliXml C:\Powershell\exportTest.xml
Run Code Online (Sandbox Code Playgroud)
我知道当这个对象被重新导入时,它被反序列化并且基本上只是一个数据容器([Deserialized.Computer] 类型)。在尝试使用我的重新序列化方法重新序列化它之前,我试图弄清楚如何对这个对象进行类型检查。
例如,如果我尝试投射 $deserializedComputer 它告诉我:
Cannot convert value "Computer" to type "Computer". Error: "Cannot convert the "Computer" value of type "Deserialized.Computer" to type
"Computer"."
Run Code Online (Sandbox Code Playgroud)
我明白为什么不能强制转换,我只是使用错误消息指出该对象知道它的类型为 [Deserialized.Computer]
我找不到从 $deserializedComputer.getMember() 返回的任何内容表明它是 [Deserialized.Computer] …
powershell serialization xml-deserialization deserialization powershell-5.0
我有一个 powershell 类,我试图在使用新的 Powershell 5 类时获得 write-debug 和 write-verbose 输出。
例如:
class TestWriteDebug
{
TestWriteDebug()
{
Write-Debug "Constructor called"
}
verboseOutput()
{
Write-Verbose "Method `"verboseOutput()`" was called"
}
}
Run Code Online (Sandbox Code Playgroud)
我通过 [TestWriteDebug]::new() 调用它
$test = [TestWriteDebug]::new()
$test.verboseOutput()
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄清楚在创建对象或调用它的方法时如何传递 -debug 和 -verbose 标志,有人能告诉我这是如何实现的吗?
感谢您的帮助。