深度复制 PSObject
我有一个 powershell 脚本,在其中执行以下操作
$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 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;
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,这是一个更短、可能更清晰的版本(我非常喜欢):
注意:
然而,奇怪的是,它并没有保持有序哈希表的顺序。
将输出:
虽然对于其他类型它工作得很好:
Note that here is a shorter, maybe a bit cleaner version of this (that I quite enjoy):
Note:
However, weirdly, it does not keep the ordering of ordered hashtables.
Will output:
While with other types it works just fine:
为了获得真正的深层副本,我们可以使用二进制序列化(假设所有数据都是可序列化的;对于来自 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):
这是我用作函数的更短的函数:
Here's an even shorter one that I use as a function: