如何在 powershell 中组合这些代码?

How can I combine these codes in powershell?

        (Get-NetUDPEndpoint |
        Select-Object   LocalPort, OwningProcess
    ) + (Get-NetTCPConnection |
        Select-Object  LocalPort, OwningProcess
    ) |
        Sort-Object LocalPort, LocalAddress

Get-WmiObject win32_service | Select-Object Name, ProcessId

I want to combine the above two codes and output like below

 Name                    LocalPort OwningProcess       
 application name        135          1148
 application name        135          1148
 application name        137             4
 application name        138             4
 application name        138          2084
 application name        139             4
 application name        445             4
 application name        500          3932
 application name        500          3932

Thank you

首先构建两个将进程 ID 映射到进程和服务的字典:

$processes = @{}
Get-Process |ForEach-Object { $processes[$_.Id] = $_ }

$services = @{}
Get-CimInstance Win32_Service |ForEach-Object {
  # multiple services might share a process host, make sure we always store or update an array
  if(-not $services.ContainsKey($_.ProcessId)){
    $services[$_.ProcessId] = @( $_ )
  } else {
    $services[$_.ProcessId] += $_
  }
}

既然我们已经有了进程 ID 到进程和服务实体的便捷映射,我们可以使用 calculated properties 来根据 PID 解析名称:

@(
  Get-NetUDPEndpoint
  Get-NetTCPConnection
) |Select @{Name='Process';Expression={ $processes[[int]$_.OwningProcess].Name }},@{Name='Services';Expression={ $services[$_.OwningProcess].Name }},LocalPort,OwningProcess