# set default counts as zero
$totalAgentCount = 0
$UnavailableAgentsCount = 0
$UnmonitoredAgentsCount = 0
$HealthyAgentsCount = 0
$CriticalAgentsCount = 0
$WarningAgentsCount = 0
# get the agent data and put it in a hash
$agents = Get-SCOMAgent
# if there's no agents, just simply set all counts to zero
if (!$agents)
{
# do nothing, the counts will be zero as default
}
else
{
$totalAgentCount = @($agents).Count
#map to all agents table
$allAgentsTable = @{}
$agents | % {$allAgentsTable.Add($_.DisplayName, $_.HealthState)}
#map to all heartbeat monitors table
$allHeartbeatMonitorsTable = @{}
$watcherInstances | % {$allHeartbeatMonitorsTable.Add($_.DisplayName, $_.GetMonitoringStates($monitorCollection)[0].HealthState.ToString())}
#get agents count in different states
foreach ($agent in $allAgentsTable.GetEnumerator())
{
# get count of healthy agents
if ($agent.Value -eq 'Success' -and $allHeartbeatMonitorsTable[$agent.Name] -eq 'Success')
{
$HealthyAgentsCount++
}
# get count of warning agents
elseif ($agent.Value -eq 'Warning' -and $allHeartbeatMonitorsTable[$agent.Name] -eq 'Success')
{
$WarningAgentsCount++
}
# get count of critical agents
elseif ($agent.Value -eq 'Error' -and $allHeartbeatMonitorsTable[$agent.Name] -eq 'Success')
{
$CriticalAgentsCount++
}
}
# get count of unmonitored agents
$UnmonitoredAgentsCount = @($allAgentsTable.GetEnumerator() | ? {$_.Value -eq 'Uninitialized'}).Count
# get count of unavailable agents
$UnavailableAgentsCount = $totalAgentCount - $HealthyAgentsCount - $WarningAgentsCount - $CriticalAgentsCount - $UnmonitoredAgentsCount
#check if the Unavailable agents count is negative
if ($UnavailableAgentsCount -lt 0)
{
Write-EventLog -LogName "Operations Manager" -Source "Health Service Script" -EventId 21000 -EntryType Warning -Message "AgentStateRollup script detected the Uavailable agents count is negative, script interrupted, will wait for next execution"
exit
}
}
#add a helper class to get the localized display strings
$langClass = New-Module {
$lang = (Get-Culture).ThreeLetterWindowsLanguageName
$mp = Get-SCOMManagementPack -Name Microsoft.SystemCenter.OperationsManager.SummaryDashboard
# Set localized language to ENU if the expected language is not found in MP
try
{
$temp = $mp.GetDisplayString($lang)
}
catch [Microsoft.EnterpriseManagement.Common.ObjectNotFoundException]
{
$lang = "ENU"
}