在PowerShell中查询指定进程TCP连接数遇类访问错误求助
Hey Justin, let's break down why you're running into that error and how to get the TCP connection counts you need for specific processes.
Why Get-WmiObject isn't working here
The MSFT_NetTransportConnection class is part of the modern CIM (Common Information Model) infrastructure, not the older WMI (Windows Management Instrumentation) that Get-WmiObject interacts with. Microsoft has been phasing out WMI in favor of CIM for newer system classes, so this particular class isn't accessible via the old WMI cmdlets.
The correct way to query TCP connections by process
Use Get-CimInstance instead—it's the modern replacement for Get-WmiObject and works with CIM classes like MSFT_NetTransportConnection. Here's how to use it:
1. Query all TCP connections with process context
First, verify you can pull the connection data at all:
Get-CimInstance -ClassName MSFT_NetTransportConnection
This will return all active transport connections (including TCP) with details like OwningProcess (the PID of the process holding the connection), LocalAddress, RemoteAddress, and more.
2. Filter for a specific process
If you want connections for a specific process (e.g., chrome.exe), first get its PID(s), then filter the results:
# Get all PIDs for the target process $targetPids = (Get-Process -Name "chrome").Id # Filter connections to only those owned by the target process Get-CimInstance MSFT_NetTransportConnection | Where-Object { $_.OwningProcess -in $targetPids }
3. Count connections per process (bonus)
If you want a quick summary of how many connections each process has, you can group and count:
Get-CimInstance MSFT_NetTransportConnection | Group-Object -Property OwningProcess | ForEach-Object { # Try to get the process name for the PID $process = Get-Process -Id $_.Name -ErrorAction SilentlyContinue [PSCustomObject]@{ ProcessName = $process.Name ?? "Unknown (PID $($_.Name))" ProcessId = $_.Name ActiveConnections = $_.Count } } | Sort-Object ActiveConnections -Descending
Notes
- You might need to run PowerShell as Administrator if you want to see connections from system processes or other users' processes.
- If you only want TCP connections (not UDP), add a filter for
Protocol -eq 6(TCP uses protocol ID 6).
内容的提问来源于stack exchange,提问作者Justin Dearing

