Powershell get SCOM alerts

While creating a script to do some basic server checks, I needed to retreive some information from SCOM to see if there are any active alerts for a particular server. I used the script below to gather my data.

Make sure you installed the Microsoft Management Operations Console so the Snapin is available to Powershell


#If the SCOM server is in a different domain, you could use "get-credential" to store your domain credentials
$credSCOM = Get-Credential
#SCOM server where to connect
$RMSServer = "SCOM.FQDN.Server"
#Which server does need to be checked on active alerts?
$TargetServer = "Server2CheckFQDN.Server"

if ((Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.EnterpriseManagement.OperationsManager.Client'}) -eq $null)
{
Add-PSSnapin Microsoft.EnterpriseManagement.OperationsManager.Client -ErrorAction SilentlyContinue
}
#Credential part is only necessary when SCOM is in another domain.
if ((Get-ManagementGroupConnection | Where-Object {$_.ManagementServerName -eq $RMSServer}) -eq $null)
{
New-ManagementGroupConnection  $RMSServer -ErrorAction SilentlyContinue -Credential $credSCOM |Out-Null
}

if ((Get-PSDrive | Where-Object {$_.Name -eq 'Monitoring'}) -eq $null)
{
New-PSDrive -Name: Monitoring -PSProvider: OperationsManagerMonitoring -Root: \ -ErrorAction SilentlyContinue -ErrorVariable Err |out-null
if ($Err) { $(throw write-Host $Err) }
}

Set-Location Monitoring:\$RMSServer

#Check if server exists.
$complist = get-monitoringclass | Where-Object {$_.Name -eq ‘Microsoft.Windows.Computer’}   #Get the class Windows Computer and store it
$objects = get-monitoringobject -MonitoringClass $complist |Where-Object {$_.displayname -match $TargetServer}|select displayname -ErrorAction SilentlyContinue

if ($objects.DisplayName.Length -ne $null)
{
$alertlist = Get-Alert -Criteria "ResolutionState != 255" | where {$_.netbioscomputername -eq $TargetServer}| Select PrincipalName,Name,Description,TimeRaised,Severity
#If active alerts -eq $null
if ($AlertList -eq $null)
{
#Console output
write-host "Total Active Alerts : 0" -ForegroundColor "GREEN"
}
else
{
#Console output
write-host "Total Active Alerts: $($alertlist.Length)" -ForegroundColor "RED"
}
}
#If server doesn't exist
Else
{
#Console output
Write-Host "Server doesn't exist!" -ForegroundColor "RED"
}

#Close connections
Get-ManagementGroupConnection|Where-Object {$_.ManagementServerName -eq $RMSServer}|Remove-ManagementGroupConnection -Confirm:$false
}