问题
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?
回答1:
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
}
}
回答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
回答3:
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}}
来源:https://stackoverflow.com/questions/18255126/select-object-with-output-from-2-cmdlets