Search code examples
windowspowershellperformancecountersystem-tray

Can Powershell put counter values in the system tray?


I am trying to monitor my Wifi adapter's throughput numerically on the system tray; like so. enter image description here

I figured out the static Powershell query

((Get-Counter '\\mullick1\network interface(intel[r] centrino[r] advanced-n 6205)\bytes total/sec').countersamples).cookedvalue*8/102400000*100

But how can I get the continuous feed and how do I put it on the system tray ? I found an alternate solution in the Diskled software. But it doesn't show the actual value.


Solution

  • This is the script to render(update) a text at a notify icon.

    Customize the "Get-NotifyIconText" function as you like.

    #Requires -Version 3.0
    
    function Get-NotifyIconText {
      [DateTime]::Now.Second.ToString()
     # ((Get-Counter '\\mypc\network interface(Intel[R] 82579V Gigabit Network Connection)\bytes total/sec').countersamples).cookedvalue*8/102400000*100
    }
    
    Add-Type -ReferencedAssemblies @("System.Windows.Forms"; "System.Drawing") -TypeDefinition @"
        using System;
        using System.Drawing;
        using System.Windows.Forms;
        public static class TextNotifyIcon
        {
            // it's difficult to call DestroyIcon() with powershell only...
            [System.Runtime.InteropServices.DllImport("user32")]
            private static extern bool DestroyIcon(IntPtr hIcon);
    
            public static NotifyIcon CreateTrayIcon()
            {
                var notifyIcon = new NotifyIcon();
                notifyIcon.Visible = true;
    
                return notifyIcon;
            }
    
            public static void UpdateIcon(NotifyIcon notifyIcon, string text)
            {
                using (var b = new Bitmap(16, 16))
                using (var g = Graphics.FromImage(b))
                using (var font = new Font(FontFamily.GenericMonospace, 8))
                {
                    g.DrawString(text, font, Brushes.Black, 0, 0);
    
                    var icon = b.GetHicon();
                    try
                    {
                        notifyIcon.Icon = Icon.FromHandle(icon);
                    } finally
                    {
                        DestroyIcon(icon);
                    }
                }
            }
        }
    "@
    
    $icon = [TextNotifyIcon]::CreateTrayIcon()
    while ($true) {
       $text = Get-NotifyIconText
       [TextNotifyIcon]::UpdateIcon($icon, $text)
       [Threading.Thread]::Sleep(1000)
    }