问题描述
我有一个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中数据的不同副本,以执行几种不同的操作。从某种意义上说,我在。我可以使用,然后调用在数组的每个成员上。然后,我可以使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!