2

I have a problem with a sample of code I am writing. It is a bit of a simple question but it is an issue that has taken some time, which I do not have. I already tried the stackoverflow relevant questions and search but did not find anything that helps a lot.

I have the following code:

#Importing some file from a csv to a variable
$output = import-csv -LiteralPath ...some file imports OK

##
#Copy the layout of the csv imported for further processing..
##
$extraOut = $output.clone() 
$extraOut | ForEach-Object {
$_.innerlinks1 = ""
$_.innerlinksurl1 = ""
}

When I try to print out the value of $output, by using $_ I get the empty strings that I previously assigned (which I do not want). Why does this happen?

#Trying to print out $output should have data and not empty strings.
$output | ForEach-Object { Write-Host $_ }

Any help, or code that allows to copy the structure of an Import-csv result (with or without PSObject cloning) would also be great.

NOTE: After finding a helpful answer, I also think that the problem needs more detailed scripting since there is a lot of empty strings in my file that might cause additional issues in the future.

Hskdopi
  • 51
  • 1
  • 7
  • 2
    Array's clone method performs a *shallow* copy, it doesn't clone elements. Look for examples of proper (deep) cloning, there are lots. – wOxxOm Jun 23 '17 at 08:46
  • I did try using `.PSObject.copy()` but got the same results. I am already on to it. – Hskdopi Jun 23 '17 at 08:59
  • @MathiasR.Jessen I did try that in a ForEach-Object but did not work as expected. Yes it is an array of one level of objects like so: `@{name=;name2=} @{name=;name2=} etc..` – Hskdopi Jun 23 '17 at 09:09

1 Answers1

1

I use the answer in this link whenever I need to deep copy an array. To quote the original answer:

# 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
Nick
  • 1,178
  • 3
  • 24
  • 36
  • I believe that this is the closest answer to the temporary one that I have already found. – Hskdopi Jun 23 '17 at 13:06
  • After a bit more searching I did find a couple more related answers to yours, in this [link](https://stackoverflow.com/questions/7468707/deep-copy-a-dictionary-hashtable-in-powershell) and in [GitHub as a gist](https://gist.github.com/zippy1981/2006846) – Hskdopi Jun 23 '17 at 13:09