Powershell 3 克隆一个对象有意外的结果 - 影响其他对象

Powershell 3 clone an object has unexpected results - affects other object

我正在编写的代码示例有问题。这是一个有点简单的问题,但它已经花了一些时间,而我没有。我已经尝试了 Whosebug 相关问题和搜索,但没有找到任何有帮助的东西。

我有以下代码:

#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 = ""
}

当我尝试打印出 $output 的值时,通过使用 $_ 我得到了我之前分配的空字符串(我不想要)。为什么会这样?

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

任何帮助或代码允许复制 Import-csv 结果的结构(有或没有 PSObject 克隆)也很好。

注意:找到有用的答案后,我还认为该问题需要更详细的脚本,因为我的文件中有很多空字符串,将来可能会导致其他问题。

每当我需要深度复制数组时,我都会使用 this link 中的答案。引用原答案:

# 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