PowerShell Grid Widget Helper

I already blogged about the new PowerShell Grid Widget which came with the release of UR2 for System Center 2012 R2 where we included updates for the Widgets which allow you to create richer dashboard visualization within Operations Manager.

If you look at the Walkthrough I created, there is a part where you need to create the PowerShell script that is being used for the PowerShell Grid Widget.

The creation of the PowerShell script was not as straight forward as I would liked it to be. Would not  it be great if you could just have a PowerShell function where you would input your normal PowerShell script and which would generate the script needed for the PowerShell Grid Widget on the fly?

I created a function that creates the script for the PowerShell Grid Widget with only a limited number of parameters.

Let’s walk through a scenario.

Scenario:
Create a PowerShell Grid Widget for the top 10 OpsMgr Error eventlogs on the server where you have the console running in the last 24 hours.

You would normally first start with a PowerShell script that retrieves the top 10 OpsMgr Error eventlogs on the Server where you have the Console running for the last 24 hours.

 Get-EventLog -LogName "Operations Manager" -After ((Get-Date).AddHours(-24))| where-object {$_.Entrytype -match "Error"} | 
            Select-Object EventId,Source,Message | 
                Group-Object EventId | 
                    Select-Object * -ExpandProperty Group | 
                        Select-Object count, EventId, Message -Unique |
                            Sort-Object Count -Desc |
                                Select-Object -first 10

This would result in the following:

image

After we created the script we need to “store” our “normal” PowerShell script in a scriptblock and pass this to our new Show-PSGridWidgetCode helper Function and finally pipe the result to the clipboard so we can copy the script to the Console.

 $scriptblock = {Get-EventLog -LogName "Operations Manager" -After ((Get-Date).AddHours(-24))| where-object {$_.Entrytype -match "Error"} | 
            Select-Object EventId,Source,Message | 
                Group-Object EventId | 
                    Select-Object * -ExpandProperty Group | 
                        Select-Object count, EventId, Message -Unique |
                            Sort-Object Count -Desc |
                                Select-Object -first 10
}


Show-PSGridWidgetCode -scriptblock $scriptblock -id Message | clip

image

image

Result:

image

If you want to start playing with the new PowerShell Helper Function Show-PSGridWidgetCode you need to save the following script as PowerShellGrid.ps1

 # ---------------------------------------------------
# Script: D:\PowerShellGrid_v0.3.ps1
# Version: 0.4
# Author: Stefan Stranger
# Date: 05/19/2014 21:19:49
# Description: PowerShell Grid Widget Helper Function
# Comments: With the latest OM2012 UR2 update new Dashboard Widgets have been added. 
# This helper function helps with the creation of the PowerShell script code needed Grid Widget
# Links: https://blogs.technet.com/b/stefan_stranger/archive/2014/04/28/new-powershell-grid-widget-walkthrough.aspx
# Know issues:
# - First object in returned array will be used as ID property [solved]
# - If a property of an object has multiple values this will not displayed correctly [solved]
# Changes: [04-30-2014]: Added new Id Parameter. This should be an unique property of the objects
#          [05-19-2014]: Added string type to all output objects  
# Disclaimer: 
# This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. 
# **Always test in your lab first**  Do this at your own risk!! 
# The author will not be held responsible for any damage you incur when making these changes!
# ---------------------------------------------------


Function Show-PSGridWidgetCode
{
<#
.Synopsis
   Create Script code for use in new OM12R2 UR2 PowerShell Grid Widgets.
.DESCRIPTION
   The output of this function can be copied to the Operations Manager Console to create the 
   script code for creating the new PowerShell Grid Widgets.
.EXAMPLE
   Show-PSGridWidgetCode -scriptblock {Get-Service | Select Name, Status}
   This command show the script code needed to create a PowerShell Grid Widget showing the
   Windows NT Services properties Name and Status on the machine where the console is running.
   You can copy the output to the console to have a head start creating the new Widget.
   PS C:\Scripts\PS> Show-PSGridWidgetCode -scriptblock {Get-Service | Select Name, Status} -Id "Name"
        $inputobject = Get-Service | Select Name, Status
        foreach ($object in $inputobject)
        {
            $dataObject = $ScriptContext.CreateInstance("xsd://foo!bar/baz")
            $dataObject["Id"] = ($object.Name).ToString()
                        $dataObject["Name"] = ($object.Name).ToString()
            $dataObject["Status"] = ($object.Status).ToString()
            $ScriptContext.ReturnCollection.Add($dataObject)
        } 
#>
    [CmdletBinding()]
    Param
    (
        # Inputobject parameter
        [Parameter(Mandatory=$true,
                 ValueFromPipelineByPropertyName=$false,
                 Position=0)]
                 [scriptblock]$scriptblock,
        # Name parameter
        [Parameter(Mandatory=$true,
                  ValueFromPipelineByPropertyName=$false)]
                  [string]$id
                 )
                              
        $properties = ((&$scriptblock | Get-Member -MemberType Properties).name)
        #Find properties with a collection of objects
        foreach ($property in $properties)
        {
            $property = $property -join ","
            $testherestring = @"
            `$dataObject["$property"] = [String](`$object.$property)
"@
            [string]$total += "$testherestring`n"
        }

        $script = @"
        `$inputobject = $scriptblock
        foreach (`$object in `$inputobject)
        {
            `$dataObject = `$ScriptContext.CreateInstance("xsd://foo!bar/baz")
            `$dataObject["Id"] = [String](`$object.$id)
            $total            `$ScriptContext.ReturnCollection.Add(`$dataObject)
        }

"@
    
        $script 

}

After saving the script you need to dot source the script (start the script like this . .\PowerShellGrid.ps1) (dot space dot)

Now you can call the Show-PSGridWidgetcode Function from within PowerShell. I also added help for the Function.

PS C:\Scripts\PS\OM2012\PowerShellGridWidget> help Show-PSGridWidgetCode -full   NAME     Show-PSGridWidgetCode     SYNOPSIS     Create Script code for use in new OM12R2 UR2 PowerShell Grid Widgets.     SYNTAX     Show-PSGridWidgetCode [-scriptblock] <ScriptBlock> -id <String> [<CommonParameters>]         DESCRIPTION     The output of this function can be copied to the Operations Manager Console to create the     script code for creating the new PowerShell Grid Widgets.       PARAMETERS     -scriptblock< ScriptBlock>         Inputobject parameter                 Required? true         Position? 1         Default value                        Accept pipeline input? false         Accept wildcard characters? false             -id <String>         Name parameter                 Required? true         Position? named         Default value                        Accept pipeline input? false         Accept wildcard characters? false             <CommonParameters>         This cmdlet supports the common parameters: Verbose, Debug,         ErrorAction, ErrorVariable, WarningAction, WarningVariable,         OutBuffer, PipelineVariable, and OutVariable. For more information, see         about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).     INPUTS     OUTPUTS         -------------------------- EXAMPLE 1 --------------------------         PS C:\>Show-PSGridWidgetCode -scriptblock {Get-Service | Select Name, Status}             This command show the script code needed to create a PowerShell Grid Widget showing the     Windows NT Services properties Name and Status on the machine where the console is running.     You can copy the output to the console to have a head start creating the new Widget.     PS C:\Scripts\PS> Show-PSGridWidgetCode -scriptblock {Get-Service | Select Name, Status} -Id "Name"          $inputobject = Get-Service | Select Name, Status          foreach ($object in $inputobject)          {              $dataObject = $ScriptContext.CreateInstance("xsd://foo!bar/baz")              $dataObject["Id"] = ($object.Name).ToString()                          $dataObject["Name"] = ($object.Name).ToString()              $dataObject["Status"] = ($object.Status).ToString()              $ScriptContext.ReturnCollection.Add($dataObject)          }                         RELATED LINKS

The ID parameter is used for the property that is being used as the unique key that is used in the PowerShell Grid Widget.

Another example for retrieving SCOM Alerts with some filter criteria.

 $scriptblock = {
    Get-SCOMAlert -Criteria "ResolutionState = 0 AND Severity = 2 AND IsMonitorAlert = 1 AND (Owner <> 'Stefan' OR Owner IS NULL)" |
        Select Name, Severity, Priority, TimeRaised, ResolutionState
}

Show-PSGridWidgetCode -scriptblock $scriptblock -id Name | clip

image

Disclaimer:

This example is provided “AS IS” with no warranty expressed or implied. Run at your own risk. The opinions and views expressed in this blog are those of the author and do not necessarily state or reflect those of Microsoft.

**Always test in your lab first** Do this at your own risk!! The author will not be held responsible for any damage you incur when making these changes!