System Monitor by Powershell

Process Monitor

先上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
$CurrentDir = Split-Path $MyInvocation.MyCommand.Path
$file = "$CurrentDir/Monitor.csv"
$ps_name = "java"
$show_sys_cpu_rate = $false
$show_sys_mem_rate = $false

$memory_sys_total = (Get-WmiObject -Class Win32_PhysicalMemory |measure capacity -sum).Sum #(gwmi win32_computersystem).TotalPhysicalMemory
$cpu_cores = (Get-WmiObject Win32_ComputerSystem).NumberOfLogicalProcessors
# $memory_sys_total = (Get-Counter "\Memory\System Driver Total Bytes").CounterSamples | Sort-Object Path
# $memory_sys_total = $memory_sys_total[0].CookedValue
"time,CPU(%),Memory(%),CPU_$ps_name(%), Memory_$ps_name(%)" >> $file
while ($True) {
$cpu_rate_pss = (Get-Counter "\process($ps_name*)\% Processor Time").CounterSamples | Sort-Object Path
$cpu_rate_sys = (Get-Counter "\processor(_total)\% processor time").CounterSamples | Sort-Object Path
$cpu_rate_sys = $cpu_rate_sys[0].CookedValue
if($show_sys_cpu_rate -eq $false){
$cpu_rate_sys = 0
}

$memory_pss = (Get-Counter "\Process($ps_name*)\Working Set - Private").CounterSamples | Sort-Object Path

if($show_sys_mem_rate){
$memory_sys_available = (Get-Counter "\Memory\Available Bytes").CounterSamples | Sort-Object Path
$memory_sys_available = $memory_sys_available[0].CookedValue
$memory_sys = $memory_sys_total - $memory_sys_available
}else{
$memory_sys = 0
}

$cpu_rate_pss_total = 0
$memory_pss_total = 0
$cpu_rate_pss.Count
try {
For ($i = 0; $i -lt $cpu_rate_pss.Count; $i++) {
$cpu_rate_pss_total = $cpu_rate_pss_total + $cpu_rate_pss[$i].CookedValue
$memory_pss_total = $memory_pss_total + $memory_pss[$i].CookedValue
}
}catch{
Write-Output ""
}

$cpu_rate_sys = "{0:F2}" -f $cpu_rate_sys
$cpu_rate_pss_total = "{0:F2}" -f $cpu_rate_pss_total / $cpu_cores

$memory_rate_sys = "{0:F2}" -f ( $memory_sys / $memory_sys_total * 100)
$memory_rate_pss_total = "{0:F2}" -f ( $memory_pss_total / $memory_sys_total * 100)

$time = Get-Date -format "MM/dd/yyyy HH:mm:ss"

Write-Output "Time=$time;CPU=$cpu_rate_sys;Mem=$memory_rate_sys;CPU($ps_name)=$cpu_rate_pss_total;Mem($ps_name)=$memory_rate_pss_total"
"$time,$cpu_rate_sys,$memory_rate_sys,$cpu_rate_pss_total,$memory_rate_pss_total" >> $file

sleep 1
}

之前也有写过监测系统CPU和内存的Powershell脚本和Python脚本,不过当时都只有监测系统的CPU和内存的占比变化,没有针对进程。

最近在做测试的时候,已经在脚本中加入了Python对进程的操作,不过因为和具体项目结合在一起,还没有时间把代码抽象出来。今天本来想着在之前Powershell脚本的基础上改一下,不过没想到踩了一些坑,主要还是不熟悉。尤其如果对C#比较了解的话,写起来会方便很多。Powershell可以直接调用.Net的许多对象和方法。

Read more