This document is part of the Operations Manager Management Pack Authoring Guide.  The Microsoft System Center team has validated this procedure as of Revision #10.  We will continue to review any changes and periodically provide validations on later revisions as they are made.  Please feel free to make any corrections or additions to this procedure that you think would assist other users.


Introduction

ScriptContext is a helper object providing required methods and properties to Windows PowerShell scripts used as data sources for dashboards in System Center 2012 Operations Manager. The object is passed as a global variable to all PowerShell scripts that run in the context of a dashboard.

The ScriptContext object only exists when a script is run in the context of the dashboard, so there is no ability to test it prior to using it in the management pack. You can test your script with the lines using ScriptContext to at least ensure that it is collecting and returning proper data.

Properties

The ScriptContext object has the properties in the following sections.

ManagementGroup Property

The ManagementGroup property of the ScriptContext object returns the management group object that the script is running in.

Context Property

The Context property of the ScriptContext object holds a string that the script can write to and then retrieve the next time that the script is run.

The Context property persists for the life of the dashboard. It is created when the script is first run and then available each time the component is refreshed.

ReturnCollection Property

A Windows PowerShell script that acts as the data source of a dashboard returns data to the dashboard by creating a Return Collection. The Return Collection is a collection of data objects with the information that should be displayed in the dashboard component. This output is then typically written by the component calling the PowershellDataSource component to a variable in the Component Implementation where it can be used by another component for display.

The Return Collection persists for the life of the dashboard. It is created when the script is first run and then available each time the component is refreshed. The PowershellDataSource component allows you to define a script to run when the component is first initialized and a separate script when it is refreshed. This gives you the option to create a refresh script that reads the return collection and modifies it with only required changes which may be more efficient than the initial script which must collect all data.

The Return Collection from the script is managed by the ReturnCollection property of the ScriptContext object. This property has multiple properties and methods of its own for working with the collection returned from the script.

The properties of the ReturnCollection object are defined in the following table.

Property

Description

Count

Integer value with the number of data objects currently contained in the return collection..

IsReadOnly

If IsReadOnly is set to False, then instances can be added or removed from the collection.


The methods of the ScriptContext object are defined in the following table.

Method

Description

Add(DataObject item)

Adds the DataObject to the collection returned from the script.

Clear()

Clears all objects in the return collection.

Contains(DataObject item)

Returns a Boolean value specifying whether the DataObject is currently in the return collection.

Remove(DataObject item)

Removes the DataObject from the return collection.

RevertCollection()

Reverses any Add, Remove, or Update actions performed on the collection since the script started.


Methods

The following sections define the methods of the ScriptContext object.

InvokeGenericMethod

Provides the ability to invoke a generic method on an object since Windows PowerShell doesn’t support this ability. Returns Object.


Parameter

Type

Description

Instance

Object

The specific object instance to work with.

genericMethodName

String

Name of the generic method.

genericMethodTemplateTypes

Type[]

The template types to pass to the generic method.

parameters

Object[]

Values for parameters required by the method. May not be null.


InvokeGenericMethodWithTypes

Provides the ability to invoke a generic method on an object since Windows PowerShell doesn’t support this ability. With this method, you must specify the parameter types. Returns Object.


Parameter

Type

Description

Instance

Object

The specific object instance to work with.

genericMethodName

String

Name of the generic method.

genericMethodTemplateTypes

Type[]

The template types to pass to the generic method.

parameterTypes

Type[]

The types for the parameters being passed into the method.

parameters

Object[]

Values for parameters required by the method. May be Null.


CreateFromObject

Creates a DataObject from the given monitoring object. Returns DataObject.

Parameter

Type

Description

inputObject

Object

The object to create the DataObject from.

properties

String

Comma delimited list of the properties of the object to include in the DataObject. In the form <Data Object Property> = <Monitoring Object Property>. For example, Id=Id,MyDisplayName=DisplayName”

propertyCollectionProperties

String

Comma delimited list of the class properties of the object to include in the DataObject. In the form <Data Object Property> = <Class Property>. For example, DatabaseName=DatabaseName,MyDisplayName=DisplayName”


CreateInstance

Creates an instance of the given data type. Returns DataObject.

Parameter

Type

Description

dataTypeName

String

Name of the data type.


CreateCollection

Creates a collection that can include multiple data types. Returns DataObjectCollection.

Parameter

Type

Description

None

 -  -

Creates a collection with multiple instances of a particular type. Returns DataObjectCollection.

Parameter

Type

Description

typeName

String

Type of the instances in the collection.


CreateWellKnownType

Creates an instance of a well-known type. Returns DataObject.

The well-known types are as follows:

  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/InMaintenanceModeType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/ConnectorStatusType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/IsMonitorAlertType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/MonitoringObjectInMaintenanceModeType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/PriorityType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/SeverityType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/TimeSinceBaseDateTime
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/HealthStateType
  • Microsoft.SystemCenter.Visualization.OperationalDataTypes/MonitoringObjectHealthStateType

Parameter

Type

Description

dataTypeName

String

Name of the type from the list below. The details of each type are defined in the Visualization Library.

Value

Object

Object with defined properties to assign to the instance.


Example

An example script is available in the sample Dashboard management pack and is copied below. This script collects performance data for SQL Server databases on one or more database engines and returns the data to be used in a dashboard component. Notes about the ScriptContext object and the resulting DataObject are as follows:

  • For each of the databases, the CreateFromObject method of the ScriptContext object is used to create a DataObject for each database. This object includes Id, Health State, and Display Name properties of the database. The same name is used for each property in the new object.
  • A function in the script is called to retrieve performance data for the instance and add it to the DataObject.
  • Once the DataObject for each database has been configured, it is added to the ReturnCollection.

Param($dbEngines)
 
# Function to add the DB Free Space to the data object.
# Parameters:
#   dataObject - The data object that is being modified.
#   instance   - The database instance.  This is used to get the performance data.
#   criteria   - Criteria to use for retrieving the performance data.
#   startTime  - The starting time of the performance data to collect.
#   endTime    - The ending time of the performance data to collect.
 
Function SetPerfCounterLastValue($dataObject,$instance,$criteria,$counterName,$startTime,$endTime)
{
     
    # Get the performance data using the GetMonitoringPerformanceData method on the instance object.
    # This method requires the criteria for which data should be returned.
    $performanceDataCollection = $instance.GetMonitoringPerformanceData($criteria)
     
    # End the function and return null if no perf data found.
    if ($performanceDataCollection.Count -ne 1)  { return $null }
 
    # If a collection of performance is returned, we only want the first.
    $performanceData = $performanceDataCollection[0]
 
    #Limit our data to the counters collected between the specified times.
    $dataCollection = $performanceData.GetValues($startTime, $endTime)
     
    # End the function and return null if no perf data between dates.
    if ($dataCollection.Count -lt 1)  { return $null }
 
    # We only want the last collected value added to the data object.
    $lastDataValue = $dataCollection[$dataCollection.Count - 1].SampleValue
    $dataObject[$counterName] = [Math]::Round($lastDataValue, 4)
}
 
# The class we're working with is SQL Server database.  This is the base class for all versions of SQL Server.
$class = Get-SCOMClass -Name Microsoft.SQLServer.Database
 
# If DB Engines not specified, then get all databases from all engines.
if ($dbEngines -eq $null -or $dbEngines.length -eq 0)
{
    $databases = Get-SCOMClassInstance -Class $class
}
else
{
     
    # If DB Engines are specified, then only collect databases hosted by these engines.
    foreach($dbEngine in $dbEngines){
        $dbEngineInstance = Get-SCOMClassInstance -Id $dbEngine["Id"]
        if ($dbEngineInstance -eq $null) { continue }
        $databases = $databases + $dbEngineInstance.GetRelatedMonitoringObjects($class)
    }
}
 
# The perf APIs require a start and end time
# In this case, we specify current time as end time and two hours ago as start time.
$endTime = [DateTime]::UtcNow
$timeDiff = [TimeSpan]::FromHours(2)
$startTime = $endTime - $timeDiff
 
foreach ($database in $databases)
{
    # Create a data object for the each database specifying the database object and the properties to include.
    $dataObject = $ScriptContext.CreateFromObject($database, "Id=Id,HealthState=HealthState,DisplayName=DisplayName", $null)
     
    # These are the criteria used to fetch performance values
    # In this case, we specify all data with a particular counter name.
 
    # Call function to add the performance data to the data object.
    # We need the counters for the total free space in the database.  One counter for the MB and one counter for the percentage.
    $freeSpacePerfCriteria = New-Object Microsoft.EnterpriseManagement.Monitoring.MonitoringPerformanceDataCriteria("CounterName='DB Total Free Space (MB)'")
    SetPerfCounterLastValue $dataObject $database $freeSpacePerfCriteria 'DBFreeSpaceLast' $startTime $endTime
    $freeSpacePerfCriteria = New-Object Microsoft.EnterpriseManagement.Monitoring.MonitoringPerformanceDataCriteria("CounterName='DB Total Free Space (%)'")
    SetPerfCounterLastValue $dataObject $database $freeSpacePerfCriteria 'DBFreePctgLast' $startTime $endTime
     
    # Add the data object to the Return Collection
    # The Return Collection holds the output of the script where it can be accessed by the component.
    $ScriptContext.ReturnCollection.Add($dataObject)
}

See Also