Microsoft.SystemCenter.Visualization.GetTopNEntitiesByPerf.ps1 (Resource)

Element properties:

TypeResource
File NameGetTopNEntitiesByPerf.ps1
AccessibilityInternal

Source Code:

<Resource ID="Microsoft.SystemCenter.Visualization.GetTopNEntitiesByPerf.ps1" Accessibility="Internal" FileName="GetTopNEntitiesByPerf.ps1"/>

File Content: GetTopNEntitiesByPerf.ps1

#**********************Top N Entities By Perf********************************


Param($CounterQueryInfo,
$TimeInterval,
$NumberOfEntities,
$ReturnBottomN);

# Input parameters

$scopingEntities = new-object 'System.Collections.Generic.List[object]';

foreach ($MEObject in $CounterQueryInfo["ManagedEntityIds"])
{
$scopingEntities.Add($MEObject);
}

if ($scopingEntities.Length -eq 0)
{
Write-Host "Scoping entity list cannot be empty!"
exit;
}

$firstMEObject = $scopingEntities[0];

if ($firstMEObject -ne $null)
{
$scopingEntityId = $firstMEObject["Id"]
}
else
{
Write-Host "First managed entity in the counter query info cannot be null!"
exit;
}

# Input parameters


# Standard input
$scriptContext = $global:scriptContext

$mg = $scriptContext.ManagementGroup

$datawarehouse = $mg.GetDataWarehouse();


#****************************Helper Functions*********************************
#
#

function Get-ParametersTypes
#-------------------------------------------------------
# Helper to generate an array of parameter types
# from the actual parameters. Note that it won' work
# if passed argument is null or contain a null value
# in its content.
#
# Arguments:
# params - array of arguments.
#
# Returns:
# The matching array of types.
#-------------------------------------------------------
{
param (
[object[]]$params = $null
)

$paramsTypes = new-object object[] $params.Length;
$idx = 0;
foreach($p in $params)
{
$paramsTypes[$idx] = $params[$idx].GetType();
$idx = $idx + 1;
}

return $paramsTypes;
}

function Invoke-GenericMethod-WithTypes
#-------------------------------------------------------
# Makes a generic and call it returning whatever it
# returns
#
# Arguments:
# myType - Type containing the generic method.
# myMethod - Method name
# myMethodArgumentTypes - Argument types for the method (support overload)
# genericTypes - Generic passing in types
# object - Object to call the generic on
# params - Parameters for the call
#
# Returns:
# The matching array of types.
#-------------------------------------------------------
{
param (
[type]$myType,
[string]$myMethod,
[type[]]$myMethodArgumentTypes,
$genericTypes,
$object,
[object[]]$params = $null
)

$method = $myType.GetMethod($myMethod, $myMethodArgumentTypes);
$genericMethod = $method.MakeGenericMethod($genericTypes);

return $genericMethod.Invoke($object, $params);
}

function Invoke-GenericMethod
#-------------------------------------------------------
# Makes a generic and call it returning whatever it
# returns
#
# Arguments:
# myType - Type containing the generic method.
# myMethod - Method name
# genericTypes - Generic passing in types
# object - Object to call the generic on
# params - Parameters for the call
#
# Returns:
# The matching array of types.
#-------------------------------------------------------
{
param (
[type]$myType,
[string]$myMethod,
$genericTypes,
$object,
[object[]]$params = $null
)

$paramsTypes = Get-ParametersTypes($params);

return Invoke-GenericMethod-WithTypes `
$myType `
$myMethod `
$paramsTypes `
$genericTypes `
$object $params;
}

#
#
#****************************Helper Functions*********************************



function PrepareMEListXml
#-------------------------------------------------------
# This method prepares an xml string that contains the
# ids of all the instances of the target type in the
# specified group.
#
# Arguments:
# n/a
#
# Returns:
# n/a
#-------------------------------------------------------
{

[System.Collections.Generic.List[Guid]]$queryIds = new-object 'System.Collections.Generic.List[Guid]'
$queryIds.Add($scopingEntityId);

$managedEntityIdsSBuilder = new-object 'System.Text.StringBuilder';

# Create a writer to write XML to the console.
$settings = new-object 'System.Xml.XmlWriterSettings';
$settings.OmitXmlDeclaration = $true;

$writer = [System.Xml.XmlWriter]::Create($managedEntityIdsSBuilder, $settings);

# Write the book element.
[void]$writer.WriteStartElement("ManagedEntityIds");

# Add the contained elements.
foreach ($obj in $queryIds)
{
# Write the title element.
[void]$writer.WriteStartElement("Id");
[void]$writer.WriteString([Guid]$obj);
[void]$writer.WriteEndElement();
}

# Write the close tag for the root element.
[void]$writer.WriteEndElement();

# Write the XML and close the writer.
[void]$writer.Close();

$script:scopedEntityListXml = $managedEntityIdsSBuilder.ToString();
}


function InitializeStartEndTimes
#-------------------------------------------------------
# This method sets the start and end times of the query
# using the passed in time interval object.
#
# Arguments:
# n/a
#
# Returns:
# n/a
#-------------------------------------------------------
{
$startObj = $TimeInterval["StartPoint"];
$startBase = $startObj["BaseDateTime"].ToString();
$startOffsetType = $startObj["OffsetType"].ToString();
$startOffset = $startObj["Offset"].ToString();

$endObj = $TimeInterval["EndPoint"];
$endBase = $endObj["BaseDateTime"].ToString();
$endOffsetType = $endObj["OffsetType"].ToString();
$endOffset = $endObj["Offset"].ToString();

$intervalString = "<Interval><Title>CurrentInterval</Title>" +
"<Start><Base>" + $startBase + "</Base>" +
"<Offset Type='" + $startOffsetType + "'>" + $startOffset + "</Offset>" +
"</Start>" +
"<End><Base>" + $endBase + "</Base>" +
"<Offset Type='" + $endOffsetType + "'>" + $endOffset + "</Offset>" +
"</End>" +
"</Interval>";

$intervalParser = new-object 'Microsoft.EnterpriseManagement.Presentation.Controls.IntervalParserBase';

$intervalParser.Initialize($intervalString);

$script:startDateTime = $intervalParser.GetIntervalStartDateTime().ToUniversalTime();
$script:endDateTime = $intervalParser.GetIntervalEndDateTime().ToUniversalTime();
}



function InitializeParameters
#-------------------------------------------------------
# This method initializes the parameters
# using the mp name and the type name in the type
# parameter's FullyQualifiedName field.
#
# Arguments:
# n/a
#
# Returns:
# n/a
#-------------------------------------------------------
{
InitializeStartEndTimes;

PrepareMEListXml;

# set order by value
if ($ReturnBottomN -eq 1)
{
$script:orderByParamValue = 0;
}
else
{
$script:orderByParamValue = 1;
}

#set aggregation type
$timeSpan = $endDateTime.Subtract($startDateTime);

if ($timeSpan.TotalHours -gt 24)
{
$script:aggregationType = 30;
}
else
{
$script:aggregationType = 20;
}
}


function CallSP
#-------------------------------------------------------
# This method calls the DW sp.
#
# Arguments:
# n/a
#
# Returns:
# n/a
#-------------------------------------------------------
{
$params = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameterCollection;

$paramMG = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("ManagementGroup", $mg.Id);
$paramScopedEntityList = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("ScopedContainerEntityListXml", $script:scopedEntityListXml);
$paramStartTime = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("StartTime", $startDateTime);
$paramEndTime = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("EndTime", $endDateTime);
$paramNumEntities = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("NumEntities", $NumberOfEntities)
$paramObjectName = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("ObjectNamePattern", $CounterQueryInfo["PerformanceObjectName"])
$paramCounterName = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("CounterNamePattern", $CounterQueryInfo["PerformanceCounterName"])
$paramInstanceName = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("InstanceNamePattern", $CounterQueryInfo["PerformanceCounterInstanceName"])
$paramAggregationType = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("AggregationType", $aggregationType)
$paramOrderBy = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("OrderBy", $script:orderByParamValue)
$paramReturnBottomEntities = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("ReturnBottomEntities", $ReturnBottomN)
$paramTypeofReturnValues = new-object Microsoft.EnterpriseManagement.Warehouse.StoredProcedureParameter("TypeofReturnValues", 1)


[void]$params.Add($paramMG);
[void]$params.Add($paramScopedEntityList);
[void]$params.Add($paramStartTime);
[void]$params.Add($paramEndTime);
[void]$params.Add($paramNumEntities);
[void]$params.Add($paramObjectName);
[void]$params.Add($paramCounterName);
[void]$params.Add($paramInstanceName);
[void]$params.Add($paramAggregationType);
[void]$params.Add($paramOrderBy);
[void]$params.Add($paramReturnBottomEntities);
[void]$params.Add($paramTypeofReturnValues);

$script:rs = $datawarehouse.GetDataWarehouseData("SDK.Microsoft_SystemCenter_Visualization_Library_TopNEntitiesByPerfGet", $params);
}




function SetOutput
#-------------------------------------------------------
# This method adds the entities returned from the DW
# to the return collection.
#
# Arguments:
# n/a
#
# Returns:
# n/a
#-------------------------------------------------------
{
$newEntityList = @()

if ($script:rs -eq $null)
{
throw ("Result set is null!")
}

#Calculate the new entity collection
foreach($result in $rs.Results)
{
if ($result -eq $null)
{
throw ("Result is null")
}

if ($result.Values -eq $null)
{
throw ("Result.Values is null")
}

# Get the MonitoringObject with the Id we get from db.
$me = Get-SCOMClassInstance -Id $result.Values[0]

# Create an IDataObject from the MonitoringObject with properties Id and DisplayName
$dataObject = $scriptContext.CreateFromObject($me, "Id=Id,DisplayName=DisplayName,Path=ExtendedPath", $null)

# Set the extended properties of the IDataObject

$dataObject["Value"] = $result.Values[2];
$dataObject["ObjectName"] = $result.Values[3];
$dataObject["CounterName"] = $result.Values[4];
$dataObject["InstanceName"] = $result.Values[5];

# Add the IDataObject to the new entity list
# This will be used to set the return collection to the desired state

$newEntityList += $dataObject
}

$scriptContext.ReturnCollection.UpdateCollection($newEntityList)
}


function Main
{
$message = "GetTopNEntitiesByPerf.ps1: Starting execution -- " + [DateTime]::UtcNow.ToString();
Write-Host $message

# Initialize the parameters
InitializeParameters;

$message = "GetTopNEntitiesByPerf.ps1: After initializing parameters -- " + [DateTime]::UtcNow.ToString();
Write-Host $message

# Call the sp
CallSP;

$message = "GetTopNEntitiesByPerf.ps1: After sp is called -- " + [DateTime]::UtcNow.ToString();
Write-Host $message

# Set the output
SetOutput;

$message = "GetTopNEntitiesByPerf.ps1: After output is set -- " + [DateTime]::UtcNow.ToString();
Write-Host $message
}

Main