I need to add a member to the $_ object variable inside a ForEach-Object loop. The code iterates over each line of a CSV file. This is a great simplification of the real code.
How can I add a member to $_?
=== t.csv
f1,f2
1,for
2,now
3,time
=== t3.ps1
$x = Import-Csv -Path .\t.csv -Delimiter ','
$x
$x | ForEach-Object {
$_ = Add-Member -NotePropertyName 'f3' -NotePropertyValue 'xxx' -InputObject $_ -PassThru
}
$x
=== output PS H:\r> .\t3.ps1
f1 f2
-- --
1 for
2 now
3 time
1 for
2 now
3 time
PS H:\r> $PSVersionTable.PSVersion.ToString()
5.1.17763.1007
=. When you do a new assignment of$_, the reference back to$xis brokenFormat-Tableformatting (and the object's type doesn't have formatting data associated with it), that object's properties are locked in as the display columns. Subsequent output objects only show these properties at most, so extra properties added later are not displayed - indeed, this is merely a display problem - see the linked answer.