Skip to content

Operations Manager 2012 – Useful PowerShell Commands and Scripts

April 13, 2014

A collection for some PowerShell commands and scripts i use(d) on a regular basis:

Install Prerequisites 2012/2012r2 management server and/or console

$dwnld = 'C:\SCOM2012R2Prereqs'
if (!(Test-Path -path $dwnld))
 {
 New-Item $dwnld -type directory
 }
$object = New-Object Net.WebClient
$RPTurl = 'http://download.microsoft.com/download/F/B/7/FB728406-A1EE-4AB5-9C56-74EB8BDDF2FF/ReportViewer.msi'
$object.DownloadFile($RPTurl, "$dwnld\ReportViewer.msi")
 
$RPTurl = 'http://go.microsoft.com/fwlink/?LinkID=239644&clcid=0x409'
$object.DownloadFile($RPTurl, "$dwnld\SQLSysClrTypes.msi")
 
Start-Process -FilePath "$dwnld\SQLSysClrTypes.msi" -ArgumentList '/q' -Wait
Start-Process -FilePath "$dwnld\ReportViewer.msi" -ArgumentList '/q' -Wait

Install Prerequisites 2012/2012r2 web console

This script assumes the source files for the .NET installation are on S:\Software\Tools\sxs.

Import-Module ServerManager
Add-WindowsFeature NET-Framework-Core,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Http-Logging,Web-Request-Monitor,Web-Filtering,Web-Stat-Compression,Web-Mgmt-Console,Web-Metabase,Web-Asp-Net,Web-Windows-Auth,Web-ASP,Web-CGI -source S:\Software\Tools\sxs -Restart
Add-WindowsFeature Web-Asp-Net45,AS-HTTP-Activation

Back-up Unsealed Management packs

Import-Module Operationsmanager

Get-SCOMManagementPack | where {$_.Sealed -eq $false} | export-SCOMmanagementpack -path C:\MPBackups

Reset Monitors for closed alerts

# $Alertname=@();
# $State=@();
# $Displayname=@();

# Import Operations Manager Module and create Connection
Import-Module OperationsManager
New-SCOMManagementGroupConnection <managementgroup name>

$alerts=get-scomalert -Criteria "Severity!=0 AND IsMonitorAlert=1 AND ResolutionState=255"| where {$_.LastModified -ge ((get-date).AddDays(-7)).ToUniversalTime()}
if ($alerts -is [object])
{
foreach ($alert in $alerts)
{
$monitoringobject = Get-SCOMClassinstance -id $alert.MonitoringObjectId
# Reset Monitor
If (($monitoringobject.HealthState -eq "Error") -or ($monitoringobject.HealthState -eq "Warning"))
{
$monitoringobject.ResetMonitoringState()
$State+=$monitoringobject.HealthState
$Displayname+=$monitoringobject.displayname
$Alertname+=$alert.Name
}
}
}

Display primairy and failover servers for all Gateway servers:

#Display Primary and Failover Management Servers for all Gateway Servers
$GWs = Get-SCOMManagementServer | where {$_.IsGateway -eq $true}
$GWs | sort | foreach {
Write-Host "";
"Gateway MS :: " + $_.Name;
"--Primary MS :: " + ($_.GetPrimaryManagementServer()).ComputerName;
$failoverServers = $_.getFailoverManagementServers();
foreach ($managementServer in $failoverServers) {
"--Failover MS :: " + ($managementServer.ComputerName);
}
}
Write-Host "";
</span>

Configure failover for Gateway Servers:

This script can be used for configuring primairy and failover management server for a gateway. The script is run on the management server.

$primaryMS = Get-SCOMManagementServer | where {$_.Name –eq '<primairy ms>'}
$failoverMS = Get-SCOMManagementServer | where {$_.Name –eq '<secundairy ms'}
$gatewayMS = Get-SCOMManagementServer | where {$_.IsGateway -eq $true}
Set-SCOMParentManagementServer -GatewayServer: $gatewayMS -PrimaryServer: $primaryMS
Set-SCOMParentManagementServer -GatewayServer: $gatewayMS -FailoverServer: $failoverMS
</span>

Count all closed alerts created by monitors in the last X days:

$targetdate = (get-date).AddDays(-1)

(Get-SCOMAlert -criteria 'ResolutionState = "255" AND IsMonitorAlert = "True"'| Where-Object {$_.LastModified -gt $targetdate }).count

Disable a specific monitor:

$MP = Get-SCOMManagementPack -displayname "<override management pack>" | where {$_.Sealed -eq $False}
$Class = Get-SCOMClass -DisplayName "<class name>"
$Monitor = Get-SCOMMonitor -DisplayName "<monitor name>"
Disable-SCOMMonitor -Class $Class -ManagementPack $MP -Monitor $Monitor</pre>
$Monitor = Get-SCOMMonitor -DisplayName "<monitor name>"
Disable-SCOMMonitor -Class $Class -ManagementPack $MP -Monitor $Monitor

Enable a specific monitor:

$MP = Get-SCOMManagementPack -displayname "<override management pack>" | where {$_.Sealed -eq $False}
$Class = Get-SCOMClass -DisplayName "<class name>"
$Monitor = Get-SCOMMonitor -DisplayName "<monitor name>"
Enable-SCOMMonitor -Class $Class -ManagementPack $MP -Monitor $Monitor</pre>
$Monitor = Get-SCOMMonitor -DisplayName "<monitor name>"
Enable-SCOMMonitor -Class $Class -ManagementPack $MP -Monitor $Monitor

Turn on Agent proxy for all agents where it is disabled:

get-SCOMagent | where {$_.ProxyingEnabled -match "False"} | Enable-SCOMAgentProxy

Turn on Agent proxy by default for all new agents:

add-pssnapin "Microsoft.EnterpriseManagement.OperationsManager.Client";
new-managementGroupConnection -ConnectionString:scomserver.domain.com;
set-location "OperationsManagerMonitoring::"; 
Set-DefaultSetting -Name HealthService\ProxyingEnabled -Value True
Advertisements

From → System Center

5 Comments
  1. Tommy permalink

    Hi,
    Using the “Reset Monitors for closed alerts” script, it returns:
    Method invocation failed because […] doesn’t contain a method named ‘op_Addition
    Any help is welcome, thanks.
    Regards

    • Hi Tommy,

      This PowerShell script needs to be run with the Opererations Manager module loaded.
      Is this what you did?

      • Tommy permalink

        Hi Marthijn,
        Sure i did 🙂 But i managed it to ‘fix’ it using a different script:

        #
        # Load the OperationsManager module, this is a little bit trickier than usual
        # as the SCOM Console has not been installed on this server
        #
        # Get the current module path
        $p = [Environment]::GetEnvironmentVariable(“PSModulePath”)

        #Add to the existing path the additional path to our module
        $p += “;C:\Program Files\System Center 2012\Operations Manager\Powershell\”

        #Set the new path to the PSModulePath variable
        [Environment]::SetEnvironmentVariable(“PSModulePath”,$p)

        #
        # Load powershell extensions for SCOM 2012
        import-module OperationsManager

        #
        # Connect to the management group
        Start-OperationsManagerClientShell -ManagementServerName: “SERVERNAME”

        # Amount of hours
        $AgeHours = 24

        #get closed alerts – modify this as needed (e.g. limit by date)
        $alerts = Get-SCOMAlert -Criteria ‘ResolutionState = ”255” AND IsMonitorAlert = ”True”’ | where {$_.LastModified -le (Get-Date).addhours(-$AgeHours)}

        #empty array to store output of resets, counter variables
        $results = @()
        $count = 0
        $totalCount = $alerts.Count

        #loop through the alerts
        ForEach($alert in $alerts){

        #Get the monitor
        $monitor = Get-SCOMMonitor -id $alert.MonitoringRuleId

        #get info
        $computer = [string]$alert.NetbiosComputerName
        $monitorName = [string]$monitor.DisplayName

        #write progress and increment the counter
        Write-Progress -Activity “Reseting Health” -Status “Computer: $computer Monitor: $monitorName” -PercentComplete ($count / $totalCount * 100)
        $count++

        #only continue if we got a monitor object back
        if($monitor){

        #Get the monitoring object
        Get-SCOMMonitoringObject -id $($alert.MonitoringObjectId) | foreach {

        #Only reset if not success
        if($_.healthState -ne “Success”){

        #Reset the monitoring
        $results += $_.ResetMonitoringState($monitor)

        }
        }

        }

        }

        Regards
        Tommy

  2. eve permalink

    Hi,

    Is there any way I could configure monitoring rules in SCOM 2012 by using powershell?

    Thank you.

    • Hi Eve,

      There are many configurations you can do with PowerShell. Could you be a bit more specific in what you would like to accomplish?

      Best regards,

      Marthijn.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: