Lucas
Lucas

Reputation: 14969

How do I pipe a property of a PowerShell cmdlet output into an input of a different cmdlet?

The specific use case is:

Get-NetTCPConnection -State Listen -LocalPort 6005 |
    Get-Process -PID ???

Where ??? is the OwningProcess property of the output from the first cmdlet.

Upvotes: 0

Views: 2450

Answers (3)

TheMadTechnician
TheMadTechnician

Reputation: 36342

You have a couple options here that I can see. First, and simplest, you can pipe it to a ForEach-Object loop, and run Get-Process in that:

Get-NetTCPConnection -State Listen -LocalPort 6005 | 
    ForEach-Object {
        Get-Process -PID $_.OwningProcess
    }

Alternatively if you run Get-Help Get-Process -PArameter Id you can see that the Id parameter accepts values from the pipeline by property name, so you could create that property, and just pipe directly to Get-Process:

Get-NetTCPConnection -State Listen -LocalPort 6005 | 
    Select @{l='Id';e={$_.OwningProcess}} |
    Get-Process

Upvotes: 3

Matt
Matt

Reputation: 46730

Couple of ways to do this. When the variables cannot be matched by property you can either use a ForEach-Object loop like in Joey's answer or if you wanted to do something crazy you can tailor the pipeline object to fits the needs.

Get-NetTCPConnection -State Listen -LocalPort 6005 |
    Select-Object @{Name="PID";E={$_.OwningProcess}} | 
    Get-Process 

Since Get-Process is looking to match the pipeline variable property PID we just use a calculated property to give it what it wants.

Using ForEach-Object in this case is much simpler. Just wanted you to know there was another way.

Upvotes: 2

Joey
Joey

Reputation: 354834

The -Id parameter accepts pipeline input by property name, so you'd have to add another property with the proper name containing the PID. While possible, I'd usually just use the direct route:

Get-NetTCPConnection | ForEach-Object { Get-Process -Id $_.OwningProcess }

Upvotes: 3

Related Questions