You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本无法显示svchost.exe命令行及CPU占用异常求助

解决svchost进程信息获取的两个问题

问题1:Get-Process返回的CommandLine为空

Get-Process cmdlet默认不会加载进程的CommandLine属性,该属性仅能通过WMI/CIM接口获取,因此直接调用会返回空值。

问题2:Win32_Process的PercentProcessorTime显示为0

Win32_Process的PercentProcessorTime字段并非实时CPU使用率,它是进程自启动以来的累计CPU时间占总系统CPU时间的百分比,多数场景下会显示0(尤其是系统采样间隔过短或进程CPU负载极低时)。要获取实时CPU使用率,需通过两次采样计算CPU时间差。

修正后的脚本

以下脚本通过Get-CimInstance获取完整进程信息,结合两次采样计算实时CPU使用率,同时返回所有你需要的字段:

# 第一次采样,记录进程ID、命令行、内存和初始CPU时间(用户态+内核态)
$firstSample = Get-CimInstance -Class Win32_Process -Filter "Name = 'svchost.exe'" |
    Select-Object ProcessId, CommandLine, WorkingSetSize, 
        @{Name='InitialCPUTime'; Expression={$_.UserModeTime + $_.KernelModeTime}}

# 等待1秒,确保两次采样有足够时间差
Start-Sleep -Seconds 1

# 第二次采样,记录最新CPU时间
$secondSample = Get-CimInstance -Class Win32_Process -Filter "Name = 'svchost.exe'" |
    Select-Object ProcessId, 
        @{Name='CurrentCPUTime'; Expression={$_.UserModeTime + $_.KernelModeTime}}

# 获取系统逻辑处理器数量
$logicalCores = (Get-CimInstance -ClassName Win32_ComputerSystem).NumberOfLogicalProcessors

# 合并采样数据,计算实时CPU使用率与内存
$results = foreach ($proc in $firstSample) {
    $currentProc = $secondSample | Where-Object ProcessId -eq $proc.ProcessId
    if ($currentProc) {
        $cpuTimeDiff = $currentProc.CurrentCPUTime - $proc.InitialCPUTime
        # 换算为百分比:(CPU时间差 / (1秒的100纳秒单位值 * 核心数)) * 100
        $cpuUsage = ($cpuTimeDiff / (10000000 * $logicalCores)) * 100
        [PSCustomObject]@{
            PID = $proc.ProcessId
            CommandLine = $proc.CommandLine
            'CPU Usage (%)' = [Math]::Round($cpuUsage, 2)
            'RAM Usage (MB)' = [Math]::Round($proc.WorkingSetSize / 1MB, 1)
        }
    }
}

# 输出到桌面文件
$results | Out-File -FilePath "$env:userprofile\Desktop\svch_list.txt"

脚本说明

  • 采用两次采样计算CPU时间差,精准获取实时CPU使用率,解决了PercentProcessorTime显示0的问题。
  • 直接从Win32_Process读取CommandLine,确保字段值完整。
  • 内存使用率通过WorkingSetSize换算为MB单位,符合需求。

内容的提问来源于stack exchange,提问作者chrz997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:22:21