1

I'm using Powershell 5 if that's relevant

When adding a property to the current item in a pipeline:

I cannot refer to $_ until I have fed it into another pipeline. Why?

# make some objects to pass around
$test = (0..3) | %{[pscustomobject]@{key1="v$_.1";key2="v$_.2"} }
#    GM = TypeName: System.Management.Automation.PSCustomObject
# trying to use the current pipeline object
$test | Add-Member @{key3=$_.key1}
$test | ft *

key1 key2 key3
---- ---- ----
v0.1 v0.2     
v1.1 v1.2     
v2.1 v2.2     
v3.1 v3.2     

# try again, this time taking the current pipeline object...
#... and then putting it into another identical looking pipeline
$test | %{ $_ | Add-Member @{key4=$_.key1} }
$test | ft *

key1 key2 key3 key4
---- ---- ---- ----
v0.1 v0.2      v0.1
v1.1 v1.2      v1.1
v2.1 v2.2      v2.1
v3.1 v3.2      v3.1

I suspect it might be that the first one is implying something automatically and I haven't told the invisible/implied function to pass on $PSItem.

1
  • All arguments evaluated before pipeline is started. [pscustomobject]@{ key1='something else' } | % { $test | Add-Member @{key3=$_.key1} }. Commented Feb 24, 2017 at 7:11

1 Answer 1

3

All arguments are evaluated in the current scope before the command starts, regardless of being used syntactically in a pipeline. So $test | Add-Member @{key3=$_.key1} uses $_ from the current scope, meaning it's not an element in $test.

To have $_ evaluated for each element in the pipeline, a new scope should be created for each element via ScriptBlock (the code in curly braces) in ForEach, Where like 1..2 | ForEach { $_ }, or in ScriptBlock parameters like Expression in select @{N='calculated property'; E={$_.foo}}.

Sign up to request clarification or add additional context in comments.

1 Comment

What you call context is usually named scope. Script blocks open a new scope, in which variables may be defined that are not there in the outer scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.