Serializing PsObject for Invoke-Command

[亡魂溺海] 提交于 2019-12-13 17:08:04

问题


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
}

回答1:


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 has an overload where you can specify the depth (for objects within objects).

These are the same methods used in implementing Export-Clixml and Import-Clixml (but those cmdlets work directly with files and not strings).




回答2:


Have you tried ConvertTo-JSON?



来源:https://stackoverflow.com/questions/32854315/serializing-psobject-for-invoke-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!