透過BAT或PowerShell抓取目前CPU總使用率 和前10名使用率嗎(PowerShell GET cpu report)
透過BAT或PowerShell抓取目前CPU總使用率 和前10名使用率嗎(PowerShell GET cpu report)
資料來源: https://share.gemini.google/H9FN2mvnIEgc
GITHUB: https://github.com/jash-git/PowerShell-GET-cpu-report
單純給程式呼叫版本[cpu_report.bat]:
@echo off
rem 強制使用 UTF-8 編碼以防亂碼
chcp 65001 >nul
rem 取得目前系統的日期與時間並格式化檔名 (格式如: 20260625 和 115500)
for /f "tokens=1-4 delims=/ " %%a in ("%date%") do (set mydate=%%a%%b%%c)
for /f "tokens=1-3 delims=:." %%a in ("%time%") do (set mytime=%%a%%b%%c)
rem 如果小時小於 10 (前方有空格),自動將空格補為 0
set "mytime=%mytime: =0%"
rem 設定動態輸出檔名
set "OutputFile=cpu_report.csv"
echo 正在進行 CPU 效能取樣並匯出為獨立 CSV 檔案...
echo 預計輸出檔名: %OutputFile%
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$cpuTotal = (Get-Counter '\Processor(_Total)\%% Processor Time' -ErrorAction SilentlyContinue).CounterSamples.CookedValue; $samples = Get-Counter '\Process(*)\%% Processor Time' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty CounterSamples; $Top10 = $samples | Where-Object { $_.InstanceName -notmatch '^_total$|^idle$' } | Group-Object InstanceName | Select-Object @{Name='ProcessName';Expression={$_.Name}}, @{Name='CPU_Usage_Percentage'; Expression={[math]::Round((($_.Group | Measure-Object CookedValue -Sum).Sum / $env:NUMBER_OF_PROCESSORS), 2)}} | Sort-Object 'CPU_Usage_Percentage' -Descending | Select-Object -First 10; $totalRow = [PSCustomObject]@{ProcessName='_Total_CPU_Usage'; CPU_Usage_Percentage=[math]::Round($cpuTotal, 2)}; $timeRow = [PSCustomObject]@{ProcessName='_Report_Generated_Time'; CPU_Usage_Percentage=(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')}; $finalReport = @($totalRow) + $Top10 + $timeRow; $finalReport | Export-Csv -Path '%OutputFile%' -NoTypeInformation -Encoding utf8; $finalReport | Format-Table -AutoSize"
echo.
echo CSV 檔案已成功儲存至:%OutputFile%
echo 提示:您可以直接按兩下該檔案用 Excel 打開。
echo.
C# 呼叫(執行) BAT(外部程式) 不要有視窗顯示
using System.Diagnostics;
public void RunBatSilently()
{
ProcessStartInfo psi = new ProcessStartInfo();
// 批次檔的路徑
psi.FileName = @"C:\YourPath\YourScript.bat";
// 若有需要傳入的參數,可使用 Arguments 屬性
// psi.Arguments = "arg1 arg2";
// 關鍵設定:隱藏命令提示字元視窗
psi.CreateNoWindow = true;
// 必須將 UseShellExecute 設為 false,CreateNoWindow 才會生效
psi.UseShellExecute = false;
// 不顯示系統啟動的視窗
psi.WindowStyle = ProcessWindowStyle.Hidden;
try
{
using (Process process = Process.Start(psi))
{
// 如果需要等待 bat 執行完畢再繼續,可取消註解下方這行
// process.WaitForExit();
}
}
catch (System.Exception ex)
{
// 錯誤處理
Console.WriteLine("執行失敗: " + ex.Message);
}
}