2

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
4
  • 2
    Use pipe instead of =. When you do a new assignment of $_, the reference back to $x is broken Commented Jul 18, 2020 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. Commented Jul 18, 2020 at 17:56
  • 1
    So it is a display issue only. The object is updated when piping into add-member Commented Jul 18, 2020 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. Commented Jul 19, 2020 at 3:14

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.