Home > Software engineering >  How can I combine these codes in powershell?
How can I combine these codes in powershell?

Time:12-03

        (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

CodePudding user response:

Start by building two dictionaries that map process IDs to processes and services:

$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]  = $_
  }
}

Now that we have a convenient mapping of process IDs to process and service entities, we can use calculated properties to resolve the names based on the PID:

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