如何用PowerShell查看进程各线程运行的CPU核心
在PowerShell中查看进程线程的运行处理器核心
需求说明
在Linux中可通过ps -mo pid,tid,psr -p<PID>命令列出指定进程的所有线程及其运行的处理器核心,示例输出:
ps -mo pid,tid,%cpu,psr -p5301 PID TID %CPU PSR 5301 - 16.9 - - 5301 10.3 0 - 5302 0.0 2 - 5303 0.0 1 - 5304 0.2 3
但使用PowerShell的Get-Process只能获取线程ID:
(Get-Process -Id 21112).Threads | Format-Table 'Id' Id -- 9992 27356 21836 14740 16252 2100
查看线程全属性也找不到对应处理器核心的信息,ProcessorAffinity并非所需内容:
(Get-Process -Id 27512).Threads | Select-Object -Property * BasePriority : 8 CurrentPriority : 9 Id : 12292 IdealProcessor : PriorityBoostEnabled : True PriorityLevel : Normal PrivilegedProcessorTime : 00:00:01.8750000 StartAddress : 0 StartTime : 2024/10/6 09:04:02 ThreadState : Wait TotalProcessorTime : 00:00:06.2500000 UserProcessorTime : 00:00:04.3750000 WaitReason : UserRequest ProcessorAffinity : Site : Container : ...
解决方案
PowerShell原生ProcessThread对象未包含线程当前运行的处理器核心信息,需借助Windows CIM或第三方模块实现:
方法1:使用CIM查询(无需额外模块)
通过Win32_Thread类获取线程的CurrentProcessor属性(对应Linux的PSR),同时可计算CPU使用率:
$targetPid = 27512 # 获取目标进程的句柄 $processHandle = (Get-Process -Id $targetPid).Handle # 查询并格式化输出 Get-CimInstance Win32_Thread | Where-Object { $_.ProcessHandle -eq $processHandle } | Format-Table ProcessId, ThreadId, CurrentProcessor, @{ Name = '%CPU' Expression = { # 将时间转换为秒并计算近似CPU使用率 $totalTime = ($_.UserModeTime + $_.KernelModeTime) / 10000000 [math]::Round($totalTime, 1) } } -AutoSize
方法2:使用第三方模块ThreadTools
安装ThreadTools模块后,可直接获取线程的核心信息和CPU使用率:
# 安装模块(仅需一次) Install-Module -Name ThreadTools -Scope CurrentUser -Force # 查询目标进程的线程信息 $targetPid = 27512 Get-ThreadWin32 -ProcessId $targetPid | Format-Table ProcessId, ThreadId, CurrentProcessor, CpuUsage -AutoSize
内容的提问来源于stack exchange,提问作者Olumide
相关产品推荐
相关产品推荐

