vmstat/mpstatのようなものを作ってみた

PowerShellの勉強として、vmstat/mpstatのようなものを作ってみました。例えば、pstat.ps1という名前で保存すれば、./pstatで1秒毎のCPU使用率が表示されます。

param($delay = 1)

$allPc = new-object System.Diagnostics.PerformanceCounter(
    "Processor", "% Processor Time", "_Total")

$usrPc = new-object System.Diagnostics.PerformanceCounter(
    "Processor", "% User Time", "_Total")

$sysPc = new-object System.Diagnostics.PerformanceCounter(
    "Processor", "% Privileged Time", "_Total")

$idlPc = new-object System.Diagnostics.PerformanceCounter(
    "Processor", "% Idle Time", "_Total")

Write-Output "all usr sys idl"

# 初回は意味をなさないので値を取得するだけで捨てる
$all = $allPc.NextValue()
$usr = $usrPc.NextValue()
$sys = $sysPc.NextValue()
$idl = $idlPc.NextValue()

while($true){
    Start-Sleep -s $delay
    $all = $allPc.NextValue()
    $usr = $usrPc.NextValue()
    $sys = $sysPc.NextValue()
    $idl = $idlPc.NextValue()
    Write-Output ([string]::Format("{0,3:f0} {1,3:f0} {2,3:f0} {3,3:f0}",
        $all, $usr, $sys, $idl))
}