a Windows PowerShell Script used to monitor the CPU/Mem info of a specified process

copy the contents below and save it as whateverName.ps1:

# this Windows PowerShell Script is used to monitor the CPU/Mem info of a specified process
# there will be a temporary .csv file during running, don't change/remove it before this script complete
# refer to .log for the final data after running
# by cbzhan@gmail.com, 2016-12-1

# if complained no privilege when execute, run this command in PowerShell Console: Set-ExecutionPolicy Unrestricted

# define the process name that want to be monitored, which can be got from Windows' taskmgr, and no need to include file suffix, e.g. .exe
$psName = "taskmgr"
# define the time interval for data collection, in seconds. generally 30 secondes will be good enough
$timeInterval = 2
# define the continuous running hours. if need input minutes, e.g. 5 minutes, use format as 5/60. if need input seconds, e.g. 5 seconds, use format as 5/3600
$rHours = 10/3600

# define output data folder path, note there must be a "\" after disk & path
$disk = "C:\"
$path = "log\"
$folder = $disk+$path

# DO NOT CHANGE BELOW IF NO NEED

# create output data folder if not exist
if (test-path $folder){echo "$folder already exit"}
else {new-item -path $disk -name $path -type directory}

# got output data file name
$ymd = get-date -format "yyyyMMdd"
$fname="monitor_"+$ymd
$fname=$fname+"_"+$psName+".log"
$outfile = "$folder"+$fname

# calculate Sample number according to running hours
$SampleNumber = $rHours*3600/$timeInterval

echo "********************************************"
echo "      Begin collecting data..."
echo "process is $psName"
echo "time interval is every $timeInterval seconds"
echo "plan running for $rHours hours"
echo "do NOT close this window!!!"

# collect the defined process' system resources cost:
# processor time can be regarded as CPU
# private bytes can be regarded as Virtual Memory
# Working Set can be regarded as Resident/Physical Memory
get-counter -counter "\process($psName)\% processor time","\process($psName)\private bytes","\process($psName)\Working Set","\process($psName)\Thread Count","\process($psName)\Handle Count" -SampleInterval $timeinterval -MaxSamples $SampleNumber | export-counter -force -fileformat CSV -path "$folder\$psName.csv"

# modify the column head name and re-export as log file
$fulltext = @(get-content $folder\$psName.csv)
$fulltext[0]='"","CPU(%)","Res Mem(byte)","Virt Mem(byte)","thread(num)","handle(num)"'
echo $fulltext | out-file $outfile

echo "data output to $outfile"
echo "      End collecting data...  "
echo "      Press any key to Exit"
echo "********************************************"
$s = Read-Host

评论

此博客中的热门博文

Windows上调试C/C++程序时自动产生coredump的设置方法

利用Gitlab的Jira issue tracker实现Jira issue自动根据Gitlab commit/merge更新状态

go用xorm去update数据库的一个坑