2

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?

3 Answers 3

4

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

+1 for the note property - I think it's more elegant when working with an object that already has a lot of properties you are interested in.
0

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}}

Comments

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.