PowerShell copy an array completely

后端 未结 5 694
别那么骄傲
别那么骄傲 2020-12-01 22:23

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

相关标签:
5条回答
  • If you're copying an array of objects/value that contains all "truthy" values, or you want to quickly filter out null and "falsey" values, then this works great:

    $FruitsNew = $FruitsOriginal|?{$_}
    
    0 讨论(0)
  • 2020-12-01 22:52

    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()
    
    0 讨论(0)
  • 2020-12-01 22:54
    # Copy the array here
    $FruitsCopy = @()
    $FruitsCopy = $FruitsCopy + $FruitsOriginal
    
    0 讨论(0)
  • 2020-12-01 23:00

    Depending on what you need to do with the objects, and if they're simple enough (as in your example), you could just replace them with a new object.

    $NewFruits = $FruitsOriginal | %{ [PSCustomObject]@{ "Tasty Fruits" = $_.Type } }

    0 讨论(0)
  • 2020-12-01 23:03

    Since Powershell 3.0, same approach as Jaco's answer but using PSSerializer.
    It uses a CliXML format compatible with Export-Clixml & Import-Clixml and personally I find it easier to read.
    In theory, supports a nested hierarchy up to [int32]::MaxValue levels-deep

    #   Original data
    $FruitsOriginal     =    Get-Fruits
    #   Serialize and Deserialize data using PSSerializer:
    $_TempCliXMLString  =   [System.Management.Automation.PSSerializer]::Serialize($FruitsOriginal, [int32]::MaxValue)
    $FruitsNew          =   [System.Management.Automation.PSSerializer]::Deserialize($_TempCliXMLString)
    #   Deep copy done.
    
    0 讨论(0)
提交回复
热议问题