Skip to content

Instantly share code, notes, and snippets.

@PanosGreg
Last active October 5, 2025 18:00
Show Gist options
  • Save PanosGreg/8fa78ffa50aac17aeaf7428debc0c262 to your computer and use it in GitHub Desktop.
Save PanosGreg/8fa78ffa50aac17aeaf7428debc0c262 to your computer and use it in GitHub Desktop.
Get the processes along with their relevant service (if any), just like "tasklist /svc"
function Get-ProcessWithService {
<#
.SYNOPSIS
Get the processes along with the relevant service associated to each process (if any)
This is the equivalent to "tasklist /svc" cmd command.
.EXAMPLE
Get-ProcessWithService | where Service | select ProcessId,Name,Service
.NOTES
WMI Query Language (WQL) WHERE Clause
https://learn.microsoft.com/en-us/windows/win32/wmisdk/where-clause
About the limited properties on the service and process CIM instances
I chose to select just a few properties by default, to reduce the overall size of the objects
You can use the CollectEverything switch to get all the information.
About why did I write this function
I was looking for the powershell way to do the tasklist /svc, and after some ddigging online
I realized there was no such option. At the time I just used the cmd command, to do the job.
But after a week or so when I had some spare time, it occured to me how to do this in PS.
#>
[cmdletbinding()]
[OutputType([Microsoft.Management.Infrastructure.CimInstance])] # <-- #root/cimv2/Win32_Process
param (
[switch]$CollectEverything
)
#Requires -Modules CimCmdlets
# define the WMI Queries (WQL) for Services and Processes
$Qry = if ($CollectEverything) {'ServiceAll','ProcessAll'} else {'ServiceBase','ProcessBase'}
$Wql = @{
ProcessAll = 'SELECT * FROM Win32_Process'
ServiceAll = 'SELECT * FROM Win32_Service WHERE State = "Running"'
ProcessBase = 'SELECT ProcessId,Name,ThreadCount,ExecutablePath,CommandLine,CreationDate,ParentProcessId FROM Win32_Process'
ServiceBase = @'
SELECT Name,DisplayName,ProcessId,StartName,State,PathName,ServiceType,StartMode
FROM Win32_Service
WHERE State = 'Running'
AND (ServiceType = 'Share Process' OR ServiceType = 'Unknown')
'@
}
# get all the services & processes
$svc,$proc = $Qry | foreach {,(Get-CimInstance -Query $Wql[$_] -Verbose:$false)}
# group the services based on their process ID
$svc | Group-Object ProcessId | foreach -Begin {$grp=@{}} -Process {$grp.Add($_.Name,$_.Group)}
# correlate the processes with their respective service (if any)
$proc | foreach {$_ | Add-Member -NotePropertyMembers @{Service = $grp[[string]$_.ProcessId]}}
# finally return the output
Write-Output $proc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment