# 監視間隔 $SampleInterval = 5 # 他のカウンターにも対応させるため、$Counterコレクションに $Counters = @( [pscustomobject]@{ Name = 'CPUUsage' Path = '\Processor Information(_Total)\% Processor Utility' #Path = '\Hyper-V Hypervisor Logical Processor(_Total)\% Total Run Time' Baseline = 10.0 Max = 100.0 } ) $History = @{} $NameWidth = [math]::Max( 'PerfCounter'.Length, ($Counters.Name | Measure-Object -Property Length -Maximum).Maximum ) + 2 # ANSI underline on/off. Format the value before adding these sequences. $UnderlineOn = "$([char]27)[4m" $UnderlineOff = "$([char]27)[24m" function Get-ValueColor { param($Value, $Counter) if ($null -eq $Value) { return } if ($Value -ge $Counter.Max) { return 'Red' } if ($Value -lt $Counter.Baseline) { return 'Blue' } if ($Value -gt $Counter.Baseline) { return 'Yellow' } } foreach ($counter in $Counters) { $History[$counter.Name] = [System.Collections.Generic.List[object]]::new() } Get-Counter -Counter $Counters.Path -SampleInterval $SampleInterval -Continuous | ForEach-Object { $sampleSet = $_ foreach ($counter in $Counters) { $sample = $sampleSet.CounterSamples | Where-Object { $_.Path.EndsWith($counter.Path, [StringComparison]::OrdinalIgnoreCase) } | Select-Object -First 1 $value = $null if ($null -ne $sample -and $sample.Status -in @(0, 1) -and -not [double]::IsNaN($sample.CookedValue) -and -not [double]::IsInfinity($sample.CookedValue)) { $value = [math]::Round($sample.CookedValue, 1) } $values = $History[$counter.Name] $values.Insert(0, $value) if ($values.Count -gt 10) { $values.RemoveAt(10) } } Clear-Host Write-Host -NoNewline ('PerfCounter'.PadRight($NameWidth) + 'Baseline'.PadLeft(8)) for ($i = 0; $i -lt 10; $i++) { Write-Host -NoNewline ('{0,7:00}' -f $i) } Write-Host foreach ($counter in $Counters) { $values = $History[$counter.Name] # Color the name using the newest value. $options = @{ NoNewline = $true } $color = Get-ValueColor -Value $values[0] -Counter $counter if ($color) { $options.ForegroundColor = $color } Write-Host ($counter.Name.PadRight($NameWidth)) @options Write-Host -NoNewline ('{0,8:F1}' -f $counter.Baseline) for ($i = 0; $i -lt 10; $i++) { if ($i -ge $values.Count) { Write-Host -NoNewline (' ' * 7) continue } $value = $values[$i] $options = @{ NoNewline = $true } $color = Get-ValueColor -Value $value -Counter $counter if ($color) { $options.ForegroundColor = $color } $text = '--' if ($null -ne $value) { $text = '{0:F1}' -f $value } $padding = ' ' * [math]::Max(0, 7 - $text.Length) if ($i -eq 0) { # Underline the newest value only, excluding its padding. $text = $UnderlineOn + $text + $UnderlineOff } Write-Host ($padding + $text) @options } Write-Host Write-Host "`nUpdated: $($sampleSet.Timestamp.ToString('HH:mm:ss')) (interval: $SampleInterval sec) | Ctrl+C to stop" } }