PowerShell 完全复制一个数组 [英] PowerShell copy an array completely

查看:25
本文介绍了PowerShell 完全复制一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建现有数组的完整副本.每次我尝试这样做时,它似乎都不起作用.问题是我正在修改新复制数组中的对象名称,但它们也在原始数组中更改..

I'm trying to create a complete copy of an existing array. Every time I try this it doesn't seem to work. The thing is that I'm modifying the Object names inside the new copied array, but they're also changed in the original array..

下面的代码被高度简化,因为除了重命名对象名称之外还有很多事情发生,但它证明了我的观点.

The code below is highly simplified as there is a lot more happening then only renaming object names but it proves the point I think.

一些示例代码:

Function Get-Fruits {
    Param (
        $Fruits = @('Banana', 'Apple', 'Pear')
    )
    foreach ($F in $Fruits) {
        [PSCustomObject]@{
            Type = $F
        }
    }
}

$FruitsOriginal = Get-Fruits

Function Rename-ObjectName {
    # Copy the array here
    $FruitsNew = $FruitsOriginal # Not a true copy
    $FruitsNew = $FruitsOriginal | % {$_} # Not a true copy
    $FruitsNew = $FruitsOriginal.Clone() # Not a true copy

    $FruitsNew | Get-Member | ? MemberType -EQ NoteProperty | % {

        $Name = $_.Name

        $FruitsNew | % {
            $_ | Add-Member 'Tasty fruits' -NotePropertyValue $_.$Name
            $_.PSObject.Properties.Remove($Name)
        }
    }
}

Rename-ObjectName

所需的结果是 2 个完全独立的数组.

The desired result is 2 completely separate arrays.

$FruitsOriginal

Type
----
Banana
Apple
Pear

$FruitsNew

Tasty fruits
------------
Banana
Apple
Pear

感谢您的帮助.

推荐答案

你可以使用序列化来深度克隆你的数组:

You can use serialisation to deep clone your array:

#Original data
$FruitsOriginal = Get-Fruits

# Serialize and Deserialize data using BinaryFormatter
$ms = New-Object System.IO.MemoryStream
$bf = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
$bf.Serialize($ms, $FruitsOriginal)
$ms.Position = 0

#Deep copied data
$FruitsNew = $bf.Deserialize($ms)
$ms.Close()

这篇关于PowerShell 完全复制一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆