2

If I have a script like this:

$searchfor = @("wininit","TeamViewer")
Get-Process $searchfor | % { 
    Get-nettcpconnection -OwningProcess $_.ID |
    select @{Name='Process';Expression={(Get-Process -Id $_.OwningProcess).ProcessName }}
}

how can I access the properties that Get-Process $searchfor returned in my select-object?

You can see, in the select expression, I need to do the get-process a second time, even though I feel like I already passed the information to foreach-object

I know i could use foreach($x in $y) instead of foreach-object but is there any way to get the properties of the outside object, when working with pipes?

1
  • save the Get-NetTcpConnection to a $Var. do NOT pipe it to the Select-Object as that will replace the 1st Get-Process object with the G-NTC object. at that point you should have both the saved $Var and the Get-Process object available for use in your Select-Object calculated properties. Commented Feb 19, 2019 at 16:01

1 Answer 1

2

Use the -PipelineVariable (-pv) common parameter (PSv4+) to make each Get-Process output object available inside a script block of a subsequent pipeline stage:

$searchfor = 'wininit', 'TeamViewer'
# -PipelineVariable proc makes $proc available in script blocks later.
Get-Process $searchfor -PipelineVariable proc | % { 
  Get-NetTCPConnection -OwningProcess $_.ID |
    Select-Object @{Name='Process'; Expression={ $proc.ProcessName }}
}

Note:

  • The variable name must be specified without $ (-PipelineVariable proc rather than
    -PipelineVariable $proc)

  • (Sensibly) the variable is local to the pipeline (goes out of scope when the command terminates).


That said, in your case you could simply define an aux. variable inside the script block:

$searchfor = 'wininit', 'TeamViewer'
Get-Process $searchfor | % { 
  # Save the input process object in an aux. variable.
  $proc = $_
  Get-NetTCPConnection -OwningProcess $_.ID |
    Select-Object @{Name='Process'; Expression={ $proc.ProcessName }}
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.