PoshCode Archive  Artifact [768b248b11]

Artifact 768b248b11b966d96e79d02d5a5c484a5cf21b9d7e78a0d0c23c2240546c5068:

  • File Get-ProcessorGraph.ps1 — part of check-in [d6d609b625] at 2018-06-10 13:45:08 on branch trunk — previous version of this script just builds a graph of processor utilization into powershell host, but how about something more dynamic and customizable, mmm? so i rewrote my Get-ProcessorGraph function. (user: greg zakharov size: 2155)

# encoding: ascii
# api: powershell
# title: Get-ProcessorGraph
# description: previous version of this script just builds a graph of processor utilization into powershell host, but how about something more dynamic and customizable, mmm? so i rewrote my Get-ProcessorGraph function.
# version: 0.1
# type: function
# author: greg zakharov
# license: CC0
# function: Get-ProcessorGraph
# x-poshcode-id: 4735
# x-archived: 2016-07-30T12:43:20
# x-published: 2016-12-24T08:23:00
#
#
Set-Alias gpg Get-ProcessorGraph

function Get-ProcessorGraph {
  <#
    .EXAMPLE
        PS C:\>Get-ProcessorGraph
        Monitors CPU fifteen seconds.
    .EXAMPLE
        PS C:\>gpg -g Red -w 25
        Sets red color for graph and monitors CPU 25 seconds.
  #>
  param(
    [Parameter(Position=0)]
    [Alias("w")]
    [ValidateRange(10, 1000000)]
    [Int32]$WatchTime = 15,
    
    [Parameter(Position=1)]
    [ConsoleColor]$GraphColor = 'Green'
  )
  
  begin {
    $pc = New-Object Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total")

    $raw = $host.UI.RawUI
    $old = $raw.WindowPosition
    $con = $raw.WindowSize
    $rec = New-Object Management.Automation.Host.Rectangle $old.X, $old.Y, `
                                        $raw.BufferSize.Width, ($old.Y + 25)
    $buf = $raw.GetBufferContents($rec)
    
    function strip([Int32]$x, [Int32]$y, [Int32]$z, [ConsoleColor]$bc) {
      $pos = $old;$pos.X += $x;$pos.Y += $y
      $row = $raw.NewBufferCellArray(@(' ' * $z), $bc, $bc)
      $raw.SetBufferContents($pos, $row)
    }
    
    function msg([Int32]$x, [Int32]$y, [String]$text, [ConsoleColor]$fc, [ConsoleColor]$bc) {
      $pos = $old;$pos.X += $x;$pos.Y += $y
      $row = $raw.NewBufferCellArray(@($text), $fc, $bc)
      $raw.SetBufferContents($pos, $row)
    }
  }
  process {
    $i = $WatchTime
    while ($i -gt 0) {
      msg 0 1 "CPU Usage" 'Gray' 'DarkYellow'
      strip 9 1 ([Math]::Round(($pc.NextValue() * 100 / $con.Width + 1))) $GraphColor
      sleep -s 1
      $i--
      $raw.SetBufferContents($old, $buf)
    }
  }
  end {
  }
}