我有以下代碼將物件匯出到 XML 檔案,然后將其讀回并將其列印在資訊流上。
try{
# Sample object
$Person = @{
Name = 'Bender'
Age = 'At least 1074'
}
$Person | Export-CliXml obj.xml
$cliXml = Get-Content -Raw ./obj.xml
Write-Host $cliXml
} finally {
if( Test-Path ./obj.xml ) {
Remove-Item -Force ./obj.xml -EV rError -EA SilentlyContinue
if( $rError ) {
Write-Warning "Failed to remove ./obj.xml: $($rError.Exception.Message)"
}
Remove-Variable -Force $rError -EA Continue
}
}
有一個系統本地父會話,它監視此輸出的 STDOUT,并將其重建為自己會話中的物件。
注意:我知道本地PSRemoting會話可以作業,但我需要它也可以在尚未配置或不會配置PSRemoting 的系統上作業。
我想去掉中間人,而不是將物件寫入磁盤。不幸的是,Import-CliXMl它Export-CliXml是CliXml名稱中唯一的 cmdlet,到目前為止,進行一些 .NET 檔案調查并沒有發現任何結果。
有沒有辦法簡單地將物件序列化為 CliXml 字串而不先寫入磁盤?我考慮過使用,$Person | ConvertTo-Json -Compress -Depth 100但這有兩個問題:
僅捕獲最多 100 層深的嵌套物件。這是一個邊緣情況,但仍然是我想避免的限制。我總是可以使用其他庫或其他格式,但是;
我希望將它們重建為與序列化之前相同型別的 .NET 物件。使用 CliXml 重新創建物件是我知道可以完成的唯一方法。
uj5u.com熱心網友回復:
CliXml 序列化器通過[PSSerializer]類公開:
$Person = @{
Name = 'Bender'
Age = 'At least 1074'
}
# produces the same XML ouput as `Export-CliXml $Person`
[System.Management.Automation.PSSerializer]::Serialize($Person)
要反序列化 CliXml,請使用以下Deserialize方法:
$cliXml = [System.Management.Automation.PSSerializer]::Serialize($Person)
$deserializedPerson = [System.Management.Automation.PSSerializer]::Deserialize($cliXml)
uj5u.com熱心網友回復:
為了補充Mathias 的有用回答:
以 new和cmdlet的形式引入基于檔案和cmdlet的記憶體等效項原則上已獲批準,但仍在等待社區實施(從 PowerShell 7.2.1 開始)-請參閱GitHub 問題 # 3898。
Export-CliXmlImport-CliXmlConvertTo-CliXmlConvertFrom-CliXml請注意,
[System.Management.Automation.PSSerializer]::Serialize()默認遞回深度為1,而Export-CliXml默認為2; 如果需要,使用允許顯式指定遞回深度的多載(例如,[System.Management.Automation.PSSerializer]::Serialize($Person, 2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399959.html
上一篇:CSV多重過濾器
