Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

PowerShell GUI ScripBlock Monitor Script

 

I made a GUI script for monitoring PowerShell scriptblocks:

It will take and Interval in Seconds and it will show the result in a GUI datagrid, refreshed at the set interval
(by re-running the scriptBlock )

Standard if you start the Acript you get a process list refreshed every 30 seconds :

 

But that is just an example as default ! ,

This script will

  • Take any Scriptblock as a parameter, 
  • Run The Scriptblock at specified interval,
  • Convert the output to a dataTable and show it in the datagrid.
  • Alow to sort the output

Examples

 

PoSH> C:\PowerShell\Scripts\start-monitor.ps1                                                                           
                                                                                                                        
                                                                                                                 
                                                                                                                        
                                                                                                                        
PoSH> C:\PowerShell\Scripts\start-monitor.ps1 -s {get-service | select name,displayname,status}                         
                                                                                                                        
                                                                                                                 
                                                                                                                        
                                                                                                                        
PoSH> C:\PowerShell\Scripts\start-monitor.ps1 5 {1 | select @{Name='Random';Expression={(new-object random).next(100)}},
{get-date},{pwd},{"ProcessCount $((gps).count)"}}                                                                       
                                                                                                                        
                                                                                                                    
                                                                                                                        
PoSH> C:\PowerShell\Scripts\start-monitor.ps1 -s {                                                                      
>> gwmi win32_service -filter "State = 'Stopped' and startmode = 'auto'" |                                              
>> select name,displayname,state,startmode                                                                              
>> }                                                                                                                    
>>                                                                                                                      
                                                                                                                        
                                                                                                               
                                                                                                                        
                                                                                                                        
PoSH> C:\PowerShell\Scripts\start-monitor.ps1 5 {sc "TestLog$((new-object random).next(100)).log" 'foo';ls *.log | selec
t directoryname,name,length,LastWriteTime}                                                                              
                                                                                                                        
                                                                                                              
                                                                                                                        
                                                                                                                                                                                                 
PoSH>                                                                       

The latter 2 examples show how flexible you are with the scriptblocks

 See the logfile list grow in last example

 

 

 

 

the statusbar will countdown to the next refresh and you also can use Ctr-R to refresh by hand.

the Script looks like this :

*edit 22-01-'07* updated the script a part of it was missing (timer start .. add_shown ) this seems to be a problem with live writer and pasting in large "Raw HTML"  text,

thanks, to "P " for mentioning that in the comments

 

# Start-Monitor.ps1 
# PowerShell Script Monitoring form  
#
# Calls a scriptblock a a specified interval and shows output in DataGridView
#    
# Start-Monitor -interval [sec] -ScriptBlock {}
#
# /\/\o\/\/ 2007    
# http://thePowerShellGuy.com 
 
PARAM([int]$Interval=30,[ScriptBlock]$ScriptBlock={(gps | select PSResources,cpu -ExcludeProperty TotalProcessorTime)})

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")  

# Helper function to translate the scriptblock output into a DataTable

Function out-DataTable {

  $dt = new-object Data.datatable  
  $First = $true  

  foreach ($item in $input){  
    $DR = $DT.NewRow()  
    $Item.PsObject.get_properties() | foreach {  
      if ($first) {  
        $Col =  new-object Data.DataColumn  
        $Col.ColumnName = $_.Name.ToString()  
        $DT.Columns.Add($Col)       }  
      if ($_.value -eq $null) {  
        $DR.Item($_.Name) = "[empty]"  
      }  
      elseif ($_.IsArray) {  
        $DR.Item($_.Name) =[string]::Join($_.value ,";")  
      }  
      else {  
        $DR.Item($_.Name) = $_.value  
      }  
    }  
    $DT.Rows.Add($DR)  
    $First = $false  
  } 

  return @(,($dt))

}

# Make form  

$form = new-object System.Windows.Forms.form   
$form2 = new-object System.Windows.Forms.form   
$Form.text = "PowerShell Script Monitor: $ScriptBLock "   
$form.Size =  new-object System.Drawing.Size(810,410)  

# Add DataGrid

$DG = new-object windows.forms.DataGridView 
  
$DG.Dock = [System.Windows.Forms.DockStyle]::Fill 
$dg.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize 
$dg.SelectionMode = 'FullRowSelect'
$form.Controls.Add($DG) 

# Build Menu    

$MS = new-object System.Windows.Forms.MenuStrip   
$Mi = new-object System.Windows.Forms.ToolStripMenuItem("&File")   

$Msi1 = new-object System.Windows.Forms.ToolStripMenuItem("&Refresh") 
$Msi1.ShortcutKeys = 0x20052
  
$msi1.add_Click({
    $col = $dg.SortedColumn
    $SortOrder = $dg.SortOrder
    $script:dt = (&$scriptBlock | out-dataTable )
    $script:DG.DataSource = $DT.psObject.baseobject
    if ("$sortOrder" -ne 'None' ) {$dg.Sort($dg.columns[($col.name)],"$SortOrder")}
    $Rows.Text = " [ Rows : $($script:dt.rows.count) ] "
})    
$Mi.DropDownItems.Add($msi1)   

$Msi2 = new-object System.Windows.Forms.ToolStripMenuItem("&Quit")   
$msi2.add_Click({$form.close()})    
$Mi.DropDownItems.Add($msi2)   

$ms.Items.Add($mi)   
$form.Controls.Add($ms) 

# statusStrip

$statusStrip = new-object System.Windows.Forms.StatusStrip

$Rows = new-object System.Windows.Forms.ToolStripStatusLabel
$Rows.BorderStyle = 'SunkenInner'
$Rows.BorderSides = 'All'
[void]$statusStrip.Items.add($Rows)

$status = new-object System.Windows.Forms.ToolStripStatusLabel
$status.BorderStyle = 'SunkenInner'
$status.BackColor = 'ButtonHighlight'
$status.BorderSides = 'All'
$Status.Text = " [ Next Refresh in : $(new-Timespan -sec $Interval) ] [ Refresh Interval : $Interval Seconds ] "
[void]$statusStrip.Items.add($status)

$Command = new-object System.Windows.Forms.ToolStripStatusLabel
$Command.Spring = $true
$Command.BorderStyle = 'SunkenInner'
$Command.BorderSides = 'All'
$Command.Text = "$ScriptBlock"
[void]$statusStrip.Items.add($Command)

$form.Controls.Add($statusStrip)

# Make Timer 

$timer = New-Object System.Windows.Forms.Timer 
if ($interval -gt 30 ) {$timer.Interval = 5000} Else {$timer.Interval = 1000}
$SecsToInterval = $interval

$timer.add_Tick({

  $SecsToInterval -= ($timer.Interval / 1000)
 
 if ( $SecsToInterval -eq 0 ) {
    $SecsToInterval = $interval
    $Command.BackColor = 'Red'
    $statusStrip.Update()
    $col = $dg.SortedColumn
    $SortOrder = $dg.SortOrder
    $script:dt = (&$scriptBlock | out-dataTable )
    $script:DG.DataSource = $DT.psObject.baseobject
    if ("$sortOrder" -ne 'None' ) {$dg.Sort($dg.columns[($col.name)],"$SortOrder")}
    $Rows.Text = " [ Rows : $($script:dt.rows.count) ] "
  }


  $Command.BackColor = 'Control'
  $Status.Text = " [ Next Refresh in : $(new-Timespan -sec $SecsToInterval) ] [ Refresh Interval : $Interval Seconds ] "
  $statusStrip.Update()

})

$timer.Enabled = $true
$timer.Start()

# show Form  

$Form.Add_Shown({
  $script:dt = (&$scriptBlock | out-dataTable )
  $script:DG.DataSource = $DT.psObject.baseobject
  $Rows.Text = " [ Rows : $($script:dt.rows.count) ] "
  $dg.AutoResizeColumns()
  $form.Activate()
}) 

$form.showdialog()   

Try out some other commands as scriptblock, The script is pretty flexible, this way of monitoring ( Polling )is not perfect but still you might find this script very usefull in on the fly tasks, It is easy to startup and it is handy to watch some things on the fly like this.

Also I had a lot of fun testing it with different scriptblocks.

Enjoy,

 

Greetings /\/\o\/\/  


		
Published Sunday, January 21, 2007 3:47 PM by admin
Filed under: , , , ,

Comments

# re: PowerShell GUI ScripBlock Monitor Script

are you missing a $timer.Start() ?

(fun script btw..thanks)

Monday, January 22, 2007 5:48 AM by P

# re: PowerShell GUI ScripBlock Monitor Script

Hiya "P",

Thanks for the comment,

You are right I a part of the script was missing. (next to the $timer.start() also the $Form.Add_Shown({}) part )

(as Live Writer is not able to paste in a large text in HTML view mode, I missed a part of the code while pasting it in in parts.)

I updated the script, thanks for mentioning it.

Greetings /\/\o\/\/

Monday, January 22, 2007 1:09 PM by MoW

# re: PowerShell GUI ScripBlock Monitor Script

Read quickly.  Not sure what the -s flag gives me yet.

Running something like this:

.\gui_mon.ps1 120 {gci feed: -rec|?{$_.type -eq "feed"}}

Doesn't allow one to properly sort on numerical values properly.

"feed:" coming PSCX...

I do really like the concept of using script blocks as input.

Perhaps something similar for your popup watcher would be cool too!  I've take a look at it a couple of times, but am not experienced enough with .NET.

Tuesday, January 30, 2007 12:58 PM by Marco Shaw

# re: PowerShell GUI ScripBlock Monitor Script

Yes,

all Properties get outputted as text in this version, just worked out the basics.

but you can also add a type to the Datasetcolumn

glad you like it.

Greetings /\/\o\/\/

Tuesday, January 30, 2007 2:29 PM by MoW

# Using IronPython from PowerShell Part 1 : Watch folder for changes without blocking Console

This is the first part of a 6 part series about using an Hosted IronPython Engine from PowerShell to

Saturday, February 10, 2007 3:27 PM by The PowerShell Guy

# re: PowerShell GUI ScripBlock Monitor Script

Hi,

Loved the Script, Work Great with WMI Queries to.

but i throws an Error when i Try to Copy from the DataGridView.

"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made"

Monday, June 23, 2008 5:44 PM by Meiron

# re: PowerShell GUI ScripBlock Monitor Script

@ Meiron

Yep, this is a restriction of the copy to clipboard that uses OLE an requires STA mode.

In PowerShell V2 (at CTP2 now) you can run PowerShell in STA mode.

Greetings /\/\o\/\/

Wednesday, June 25, 2008 7:31 AM by MoW

# Alarm Clock - System.Windows.Form stops responding | keyongtech

# Only 10 columns in out-gridview | keyongtech

Tuesday, February 03, 2009 10:08 AM by Only 10 columns in out-gridview | keyongtech

# Episode 58 - PowerShell ISE panel « PowerScripting Podcast

Sunday, February 08, 2009 11:04 PM by Episode 58 - PowerShell ISE panel « PowerScripting Podcast
Anonymous comments are disabled