Scott H
Scott H

Reputation: 35

Odd PowerShell behavior and Add-Member

Can someone help me understand why the $_ works differently for the Add-Member function than it seems to for other PowerShell functions? There must be some nuance that I am missing here.

Using the sample CSV file below, the first 3 examples work fine. The fourth, which seems pretty straightforward, does not. The error Powershell returns is:

The variable '$_' cannot be retrieved because it has not been set.

Is this "normal" or have I miscoded something?

Thanks in advance.

Test.csv
Column1,Column2, Column3
Rock,1,abc
Paper,2,efg
Scissors,3,hij

$obj = Import-CSV "C:\test.csv"

(1) $obj | Add-Member -MemberType NoteProperty -Name IdNumber -value "ROCK" -PassThru| Format-Table

(2) $obj | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name IdNumber -value $_.Column1 ; $_} | Format-Table

(3) $obj | ForEach-Object { Add-Member -InputObject $_ -MemberType NoteProperty -Name IdNumber -value $_.Column1 ; $_ } | Format-Table

(4) $obj | Add-Member -MemberType NoteProperty -Name IdNumber -value $_.Column1 -PassThru| Format-Table

Upvotes: 0

Views: 1033

Answers (1)

Keith Hill
Keith Hill

Reputation: 202062

When you do this:

$obj | Add-Member -MemberType NoteProperty -Name IdNumber -value $_.Column1 -PassThru

You are accessing $_ outside of a pipeline bound context e.g. inside a foreach-object expression or within a scriptblock value specified for a pipeline bound parameter. The Value parameter is not pipeline bound. If it were you would be able to do this:

$obj | Add-Member -MemberType NoteProperty -Name IdNumber -value {$_.Column1} -PassThru

As it stands, the easiest way to do what you want is:

$obj | ForEach-Object { Add-Member -Inp $_ NoteProperty -Name IdNumber -Value $_.Column1 -PassThru } | Format-Table

Upvotes: 4

Related Questions