0

Is it possible to make association with running services and it processes via powershell? How can I do association in hashtable, example @{ service1 = process1 ; service2 = process1 }

seyshanbe
  • 31
  • 1
  • 4
  • You can combine `Get-CimInstance win32_service` with `Get-Process` by the `ProcessID = ID` property. – Santiago Squarzon Jun 25 '21 at 15:38
  • Using this [`Join-Object script`](https://www.powershellgallery.com/packages/Join)/[`Join-Object Module`](https://www.powershellgallery.com/packages/JoinModule) (see also: [In Powershell, what's the best way to join two tables into one?](https://stackoverflow.com/a/45483110/1701026)): `Get-Service |Join (Get-Process) -On Name -eq ProcessName -Property Status, ID, Name, DisplayName` – iRon Jun 25 '21 at 17:21

2 Answers2

1

I'm not sure if this is what you're looking for, since you're only asking for Service & Process I'm assuming you only want their Names. So here is one way you could do it:

$map = @{}

Get-CimInstance win32_service | Group-Object ProcessID |
ForEach-Object {
    
    $proccess = Get-Process -ID $_.Name
    
    foreach($service in $_.Group.Name)
    {
        if($map.ContainsKey($service))
        {
            $map[$service].Add($process.Name)
            continue
        }

        $map.Add($service,$proccess.Name)
    }
}

Usage would be as any other hashtable, you provide the Service Name as key and it will return the associated Process Name as value:

PS /> $map[($map.Keys|Get-Random)]
lsass

PS /> $map[($map.Keys|Get-Random)]
SearchIndexer

PS /> $map[($map.Keys|Get-Random)]
Idle

PS /> $map[($map.Keys|Get-Random)]
svchost
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
1
Get-CimInstance Win32_Service | ForEach-Object {
    [pscustomobject]@{
        Service = $_
        Process = Get-Process -Id $_.ProcessId
    }
} 

Or you can do some custom output

Get-CimInstance Win32_Service | ForEach-Object {
    $process = Get-Process -Id $_.ProcessId
    [PSCustomObject]@{
        ServiceName   = $_.Name
        ServiceStatus = $_.Status
        ServiceState  = $_.State
        ServicePath   = $_.PathName
        ProcessId     = $_.ProcessId
        ProcessName   = $process.Name
        ProcessPath   = $process.Path
    }
} 
Daniel
  • 4,792
  • 2
  • 7
  • 20