1

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
lit
  • 14,456
  • 10
  • 65
  • 119
  • 2
    Use pipe instead of `=`. When you do a new assignment of `$_`, the reference back to `$x` is broken – AdminOfThings Jul 18 '20 at 16:48
  • @AdminOfThings, this would still fail. Apparently, the initial output of $x prevented fhe final output of $x from having the newly added member. – lit Jul 18 '20 at 17:56
  • 1
    So it is a display issue only. The object is updated when piping into add-member – AdminOfThings Jul 18 '20 at 20:54
  • In short: if the script's first output object triggers implicit `Format-Table` formatting (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](https://stackoverflow.com/a/45705068/45375). – mklement0 Jul 19 '20 at 03:14

1 Answers1

0

Here, you are iterating on the each Column of the CSV file. And $_ is the each iterated object. And you are using '=' sign and overwriting the existing value. And also you do not need the -InputObject switch and -PassThru switch as are piping the object to Add-Member. So use this:

$x = Import-Csv -Path .\t.csv -Delimiter ','

$x | ForEach-Object {
    $_ | Add-Member -MemberType NoteProperty -Name 'f3' -Value 'xxx' 
}
$x
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 1
    The problem turns out to be that the initial output of `$x` caused the subsequent output of `$x` to not have the `f3` member. IIf line 2 is deleted, the original code works as expected. – lit Jul 18 '20 at 17:55
  • As @lit's comment implies, there was nothing wrong with the original code, so your answer doesn't help, except for simplifying the `Add-Member` call a bit. – mklement0 Jul 19 '20 at 03:18