深度复制 PSObject [英] Deep copying a PSObject
问题描述
我有一个 powershell 脚本,我在其中执行以下操作
I have a powershell script in which I do the following
$somePSObjectHashtables = New-Object Hashtable[] $somePSObject.Length;
$somePSObjects = Import-CSV $csvPath
0..($somePSObject.Length - 1) | ForEach-Object {
$i = $_;
$somePSObjectHashtables[$i] = @{};
$somePSObject[$_].PSObject.Properties | ForEach-Object {
$somePSObjectHashtables[$i][$_.Name] = $_.Value;
}
}
我需要这样做是因为我想在 CSV 中制作多个不同的数据副本以执行多个不同的操作.从某种意义上说,我正在对 PSObject.我可以使用 ForEach-Object 轻松遍历 $somePSObjectHashtables
并调用 Hashtable.Clone() 在数组的每个成员上.然后我可以使用 New-Object PSObject -Property $someHashTable[$i]
来获取 PSObject 的深层副本.
I need to do this because I want to make several distinct copies of the data in the CSV to perform several distinct manipulations. In a sense I'm performing an "INNER JOIN" on the resulting array of PSObject. I can easily iterate through $somePSObjectHashtables
with a ForEach-Object and call Hashtable.Clone() on each member of the array. I can then use New-Object PSObject -Property $someHashTable[$i]
to get a deep copy of the PSObject.
我的问题是,是否有一些更简单的方法可以在没有中间哈希表的情况下进行深度复制?
My question is, is there some easier way of making the deep copy, without an intermediary Hashtable?
推荐答案
为了获得真正的深拷贝,我们可以使用二进制序列化(假设所有数据都是可序列化的;对于来自 CSV 的数据来说肯定是这种情况):>
For getting really deep copies we can use binary serialization (assuming that all data are serializable; this is definitely the case for data that come from CSV):
# Get original data
$data = Import-Csv ...
# Serialize and Deserialize data using BinaryFormatter
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $data)
$ms.Position = 0
$data2 = $bf.Deserialize($ms)
$ms.Close()
# Use deep copied data
$data2
这篇关于深度复制 PSObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!