RB.
RB.

Reputation: 37222

Select-Object with output from 2 cmdlets

Suppose I have the following PowerShell script:

Get-WmiObject -Class Win32_Service | 
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU

This will:

Line 1: Get all services on the local machine

Line 2: Create a new object with the DisplayName and PID.

Line 3: Call Get-Process for information about each of the services.

Line 4: Create a new object with the Process Name and CPU usage.

However, in Line 4 I want to also have the DisplayName that I obtained in Line 2 - is this possible?

Upvotes: 2

Views: 1625

Answers (3)

js2010
js2010

Reputation: 27606

Using a pipelinevariable:

Get-CimInstance -ClassName Win32_Service -PipelineVariable service | 
Select @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU,@{Name='DisplayName';Expression={$service.DisplayName}}

Upvotes: 0

dugas
dugas

Reputation: 12493

A couple of other ways to achieve this:

Add a note property to the object returned by Get-Process:

Get-WmiObject -Class Win32_Service | 
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
% {
    $displayName = $_.DisplayName;
    $gp = Get-Process;
    $gp | Add-Member -type NoteProperty -name DisplayName -value $displayName;
    Write-Output $gp
} |
Select DisplayName, Name,CPU

Set a script scoped variable at one point in the pipeline, and use it at a later point in the pipeline:

Get-WmiObject -Class Win32_Service | 
Select @{n='DisplayName';e={($script:displayName =  $_.DisplayName)}},
       @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select @{n='DisplayName';e={$script:displayName}}, Name,CPU

Upvotes: 2

Bill_Stewart
Bill_Stewart

Reputation: 24585

One way to do this is to output a custom object after collecting the properties you want. Example:

Get-WmiObject -Class Win32_Service | foreach-object {
  $displayName = $_.DisplayName
  $processID = $_.ProcessID
  $process = Get-Process -Id $processID
  new-object PSObject -property @{
    "DisplayName" = $displayName
    "Name" = $process.Name
    "CPU" = $process.CPU
  }
}

Upvotes: 4

Related Questions