Operations Manager 2012 – Useful PowerShell Commands and Scripts

Install and Configure


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


Gateways


Display primary and failover servers for all gateways

# 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 "";


Configure failover for gateways

$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


Agents


Enable proxy for all agents

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


Enable agent proxy by default

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


Get Grey Agents

# Import the OperationsManager module
Import-Module OperationsManager

 

# Define the array
$GreyAgents  = @()

 

# Define the output file
$file="C:\Temp\GreyAgents.txt"

 

# Get the agent class and select the grey objects
$agent = Get-SCClass -name "Microsoft.SystemCenter.Agent"
$objects = Get-SCOMMonitoringObject -class:$agent | where {$_.IsAvailable –eq $false}

 

# Put the items in the array

ForEach ($object in $objects) {
 $GreyAgents = $GreyAgents + $object.DisplayName
}

 

# Sort the array items and display them in a grid view
$GreyAgents | sort | Out-GridView


Configure Agent failover to Gateway's


 

## This script collects the agents talking to a specific gateway server and are member for a specific domain. Then set's the failover.
## Any configured failovers are removed and replaced

 

$primaryMS = Get-SCOMManagementServer -Name '<Primairy Gateway FQDN>'
$failoverMS = Get-SCOMManagementServer -Name '<Failover Gateway FQDN>'

$agents = Get-SCOMAgent | where {$_.PrimaryManagementServerName -eq $primaryMS.DisplayName -and $_.DisplayName -match '<domain name like:  .mydomain.com>'}

foreach ($agent in $agents) {

if (($agent.GetFailoverManagementServers().DisplayName) -eq $failoverMS.DisplayName) {

    write-host -ForegroundColor Green "server $($Agent.Displayname) is ok"

    }
   
else {

    Set-SCOMParentManagementServer -Agent: $agent -FailoverServer: $failoverMS
    ## Set-SCOMParentManagementServer -Agent: $agent -PrimaryServer: $primaryMS
    write-host -ForegroundColor Red "Server $($agent.DisplayName) is aangepast"
    }

}


Maintenance


Set maintenance mode for group

#--------Begin Sample Script----------------
#
# Name: OpsMgr 2012 Group Maintenance Mode
#
# Parameters:
#
# -ScomServer: mandatory parameter containing mgmt server name (Netbios or FQDN)
# -GroupDisplayName: mandatory parameter containing display name of the target group
# -DurationInMin: mandatory parameter containing integer of desired duration in minutes
# -Reason: mandatory parameter containing reason. Acceptable values are UnplannedOther,
#           PlannedHardwareMaintenance, UnplannedHardwareMaintenance,
 
#           PlannedHardwareInstallation,
#           UnplannedHardwareInstallation, PlannedOperatingSystemReconfiguration,
#           UnplannedOperatingSystemReconfiguration, PlannedApplicationMaintenance,
#           ApplicationInstallation, ApplicationUnresponsive, ApplicationUnstable,
#           SecurityIssue, LossOfNetworkConnectivity
# -Comment: optional parameter with free text description of your choice
#
#
#*****************************************************************************
# Example: .\GroupMaintenance  -ScomServer pl-om01 -GroupDisplayName D -DurationInMin 5 -Reason UnplannedOther -Comment "Maintenance set by Group Maintenace Mode Script
 
 
param
([Parameter(Mandatory=$true)][string]$ScomServer,
[Parameter(Mandatory=$true)][string]$GroupDisplayName,
[Parameter(Mandatory=$true)][Int32]$DurationInMin,
[Parameter(Mandatory=$true)][string]$Reason,
[Parameter(Mandatory=$false)][string]$Comment)
 
 
Function ObjMaintMode ($MonitoredObject, $DurationInMin, $Reason, $Comment)
{
    If ($($MonitoredObject.InMaintenanceMode) -eq $false)
    {
        "MonitoredObject: $($MonitoredObject.DisplayName) Duration: $DurationInMin Reason: $Reason Comment: $Comment"
        $MonitoredObject.ScheduleMaintenanceMode([datetime]::Now.touniversaltime(),([datetime]::Now).addminutes($DurationInMin).touniversaltime(),"$Reason", "$Comment" , "OneLevel")
    }
    Else
    {
        $ScheduledEndTime = $MonitoredObject.GetMaintenanceWindow().ScheduledEndTime
        If ($ScheduledEndTime -lt ([datetime]::Now).addminutes($DurationInMin).touniversaltime())
        {
            "Changed maintenancemode for $($MonitoredObject.DisplayName)"
            $MonitoredObject.ScheduleMaintenanceMode([datetime]::Now.touniversaltime(),([datetime]::Now).addminutes($DurationInMin).touniversaltime(),"$Reason", "$Comment" , "OneLevel")
        }
    }
    ForEach($MObject in $MonitoredObject.GetRelatedMonitoringObjects())
    {
        ObjMaintMode $MObject  $DurationInMin  $Reason  $Comment
    }
 
}
 
Import-Module OperationsManager
New-SCOMManagementGroupConnection -ComputerName $ScomServer
 
$MonitoredObj = Get-SCOMGroup -DisplayName $GroupDisplayName
 
ObjMaintMode $MonitoredObj $DurationInMin $Reason $Comment
 
#--------End Sample Script----------------


Reset monitors with closed alerts

Everyone working with SCOM knows that when an alerts is created by a monitor and is closed without solving the issue no alert will come until the monitor is reset or maintenance mode to the object has been applied.
This can cause blanc spots in monitoring.
The Powershell script created will resets the monitor if a closed alert has been found and no new alert is active.

You could schedule this script or build it in a maintenance management pack so it runs frequently.

Thanks to Michel van der Zijden!

Import-Module OperationsManager
New-SCOMManagementGroupConnection

# Get closed alerts generated by a monitor that are not resolved by OpsMgr
$alerts=get-scomalert -ResolutionState 255 | ?{$_.IsMonitorAlert -eq $true -and $_.LastModifiedBy -ne "System"}

# Display the number of alerts found
Write-Output "Found $($alerts.count) manually closed alerts"

# Loop through all found alerts
foreach ($alert in $alerts) {
    $MonitorID = $alert.monitoringruleid
    $ObjectID = $alert.monitoringobjectid
    $monitor = Get-SCOMMonitor -Id $MonitorID
    $monitoringobject = Get-SCOMMonitoringobject -Id $ObjectID

    # Only proceed when the current object is still in an Error of Warning status.
    If (($monitoringobject.HealthState -eq "Error") -or ($monitoringobject.HealthState -eq "Warning")) {

        # Check if the monitor has an active alert, if that is not the case we will reset the monitor to trigger a new alert.
        If (get-scomalert -ResolutionState 0,100,101,102,200,247,248,249,250 | Where{$_.monitoringobjectid -eq $ObjectID -and $_.monitoringruleid -eq $MonitorID}) {
        }
        Else {
            $monitoringobject | foreach{$_.ResetMonitoringState($monitor)}
            $output = "$($alert.TimeResolved);$($alert.ResolvedBy);$($alert.Name)"
            Write-Host "Resetting monitor for alert: $($Output)"
        }
    }
}


Troubleshooting


Find the SSID for RunAs accounts

Get-SCOMRunAsAccount | Sort Name | % {
    $string = $null;$_.SecureStorageId | % { 
        $string = $string + "{0:X2}" -f $_
    }
    $_.Name;"  $string"
}


Reactie schrijven

Commentaren: 0