While doing some testing with Add-Member
, I created 'copies' of my actual data to test with, but I quickly found that Add-Member
was actually adding new properties to the original object without being told or asked to. Is this the expected behavior? If yes, how are by reference variables working in PowerShell?
Example:
# Create a CSV file
@'
Name,Title
Bob,President
Todd,Secretary
'@ > test.csv
# Load the CSV into an object
$Data = Import-Csv test.csv
# Create a duplicate of $Data (this must be the issue)
$NewData = $Data
# Add a new property to the $NewData object
$NewData | Add-Member ScriptProperty "First Initial" {$this.Name[0]}
# Check the original Object ($Data) and see the madness
$Data
# Viewing $Data as a table
Name Title First Initial
---- ----- -------------
Bob President B
Todd Secretary T
$Data | Get-Member
# Just confirming that there is indeed a MemberType of ScriptProperty that was added to $Data
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Name NoteProperty string Name=Bob
Title NoteProperty string Title=President
First Initial ScriptProperty System.Object First Initial {get=$this.Name[0];}