为调用命令序列化 PsObject [英] Serializing PsObject for Invoke-Command
问题描述
我正在寻找使用 Invoke-Command 将 PsObject 传递给远程函数的最佳或正确方法.ConvertTo-Xml 适合序列化,但没有内置的反向 cmdlet.我在网上找到的解决方案都是针对特定内容的.
I'm looking for the best or proper way to pass a PsObject to a remote function with Invoke-Command. ConvertTo-Xml is good for serializing but there is no built-in reverse cmdlet. The solutions I've found online are all content specific.
我实现了以下功能,这些功能适用于我测试过的少数对象,但看起来很笨拙.这是要咬我吗?有没有更好但仍然简单的解决方案?
I implemented the following functions which works with the few objects I tested but seems rather hacky. Is this going to bite me? Is there a better, yet still simple solution?
function Get-TmpFileName () {...}
function Serialize-PsObject($obj) {
$tmpFile = Get-TmpFileName
Export-Clixml -InputObject $obj -Path $tmpFile
$serializedObj = Get-Content $tmpFile
Remove-Item $tmpFile
$serializedObj
}
function Deserialize-PsObject($obj) {
$tmpFile = Get-TmpFileName
$obj > $tmpFile
$deserializedObj = Import-Clixml $tmpFile
Remove-Item $tmpFile
$deserializedObj
}
推荐答案
您是否知道 PowerShell 已经序列化了通过 Invoke-Command
发送的对象?
Are you aware that PowerShell already serializes objects sent through Invoke-Command
?
如果由于某种原因这还不够或对您不起作用,那么您可以直接使用自己的内置序列化:
If for some reason that isn't enough or isn't working for you, then you can use use the built-in serialization yourself directly:
$clixml = [System.Management.Automation.PSSerializer]::Serialize($object)
$object = [System.Management.Automation.PSSerializer]::Deserialize($clixml)
.Serialize
有一个重载,您可以在其中指定深度(对于对象内的对象).
.Serialize
has an overload where you can specify the depth (for objects within objects).
这些是用于实现 Export-Clixml
和 Import-Clixml
的相同方法(但这些 cmdlet 直接处理文件而不是字符串).
These are the same methods used in implementing Export-Clixml
and Import-Clixml
(but those cmdlets work directly with files and not strings).
这篇关于为调用命令序列化 PsObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!