Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 144 additions & 37 deletions docs-ref-conceptual/operationsmanager/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: This article describes the System Center Operations Manager REST AP
author: mgoedtel
ms.author: magoedte
manager: rayoflores
ms.date: 04/22/2020
ms.date: 11/1/2023
ms.custom: na
ms.prod: system-center
ms.technology: operations-manager
Expand Down Expand Up @@ -50,52 +50,159 @@ Required action, applicable for Operations Manager 2019 UR1.
![Initialize the CSRF token example](./Media/index/116854.png)

## Operations Manager REST API PowerShell example
The System Center Operations Manager (SCOM) API provides a powerful interface for automating and extending the capabilities of SCOM. This PowerShell script is designed to facilitate various operations by interacting with the SCOM API, simplifying the process of retrieving and managing data within your SCOM environment.

The script includes a set of primary functions that lay the groundwork for interacting with the API, such as initializing the base URL and setting up necessary authentication headers. It also includes a suite of optional functions for performing specific tasks, such as fetching the effective monitoring configuration for a particular object or querying for unsealed management packs.

Each function is crafted with parameters that allow for customization based on the user’s needs and will enable the script to be adapted to various SCOM environments.

The execution of the script is straightforward, with examples provided for authenticating using specific credentials or the current user's credentials. It also includes template code for outputting data in a structured JSON format for easy reading and integration with other systems or reporting tools.

### Functions
#### Primary Functions and Variable
```powershell
#Set Headers for the request
$userName ="domain\username";
$password ="Password";
$AuthenticationMode= "Network"
$scomHeaders = New-Object “System.Collections.Generic.Dictionary[[String],[String]]”
$scomHeaders.Add('Content-Type','application/json; charset=utf-8')
$bodyraw = "($AuthenticationMode):$($userName):$($password)”
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($bodyraw)
$EncodedText =[Convert]::ToBase64String($Bytes)
$jsonbody = $EncodedText | ConvertTo-Json
# You can modify the below to use HTTP or HTTPS. Replace <WebConsoleAddress> with the address for your Web Console.
$MainURL = 'http://MS02-2016.contoso-2016.com/OperationsManager'

$uriBase = 'http://<scomserver>/OperationsManager'
function Authenticate-SCOMAPI
{
param (
[PSCredential]$Credential = $null
)
# Set SCOM Header and the Body
$SCOMHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$SCOMHeaders.Add('Content-Type', 'application/json; charset=utf-8')
$BodyRaw = "Windows"
$Bytes = [System.Text.Encoding]::UTF8.GetBytes($BodyRaw)
$EncodedText = [Convert]::ToBase64String($Bytes)
$JSONBody = $EncodedText | ConvertTo-Json

# Initiate the Cross-Site Request Forgery (CSRF) token, this is to prevent CSRF attacks
$CSRFtoken = $WebSession.Cookies.GetCookies($MainURL) | ? { $_.Name -eq 'SCOM-CSRF-TOKEN' }
$SCOMHeaders.Add('SCOM-CSRF-TOKEN', [System.Web.HttpUtility]::UrlDecode($CSRFtoken.Value))

# Authentication
if ($Credential -ne $null)
{
Invoke-RestMethod -Method Post -Uri "$MainURL/authenticate" -Headers $SCOMHeaders -Body $JSONBody -Credential $Credential -SessionVariable WebSession
}
else
{
Invoke-RestMethod -Method Post -Uri "$MainURL/authenticate" -Headers $SCOMHeaders -Body $JSONBody -UseDefaultCredentials -SessionVariable WebSession
}
$script:WebSession = $WebSession
}
```

#Authenticate
$auth = Invoke-WebRequest -Method POST -Uri $uriBase/authenticate -Headers $scomheaders -body $jsonbody -UseDefaultCredentials -SessionVariable $websession
#Include CSRF Token
$csrfTocken = $websession.Cookies.GetCookies($uriBase) | ? { $_.Name -eq 'SCOM-CSRF-TOKEN' }
$scomHeaders.Add('SCOM-CSRF-TOKEN', [System.Web.HttpUtility]::UrlDecode($csrfTocken.Value))
#### Optional Functions
```powershell
# Function to fetch all installed SCOM Consoles
function Get-SCOMConsoles
{
# Criteria: Enter the displayname of the SCOM object
$Criteria = "DisplayName LIKE '%System Center Operations Manager Console%'"

# Convert our criteria to JSON format
$JSONBody = $Criteria | ConvertTo-Json

$Response = Invoke-WebRequest -Uri "$MainURL/OperationsManager/data/scomObjects" -Method Post -Body $JSONBody -WebSession $script:WebSession

# Convert our response from JSON format to a custom object or hash table
$Object = ConvertFrom-Json -InputObject $Response.Content

# Print out the object results
$Object.scopeDatas
}

# Function to fetch all Windows Servers
function Get-WindowsServers
{
$criteria = "DisplayName LIKE 'Microsoft Windows Server%'"
$JSONBody = $criteria | ConvertTo-Json

$response = Invoke-WebRequest -Uri "$MainURL/data/scomObjects" -Method Post -Body $JSONBody -WebSession $script:WebSession
return ($response.Content | ConvertFrom-Json).scopeDatas
}

# Function to fetch the state of the Management Group
function Get-ManagementGroupState
{
$query = @(@{
"classId" = ""
"criteria" = "DisplayName = 'Operations Manager Management Group'"
"displayColumns" = "displayname", "healthstate", "name", "path"
})

$JSONQuery = $query | ConvertTo-Json
$response = Invoke-RestMethod -Uri "$MainURL/data/state" -Method Post -Body $JSONQuery -ContentType "application/json" -WebSession $script:WebSession
return $response.Rows
}

# Function to fetch Unsealed Management Packs
function Get-UnsealedManagementPacks
{
$response = Invoke-WebRequest -Uri "$MainURL/data/UnsealedManagementPacks" -Method GET -WebSession $script:WebSession
return $response.Content | ConvertFrom-Json
}

#Examples to Invoke the required SCOM API
# Function to fetch Effective Monitoring Configuration by GUID
function Get-EffectiveMonitoringConfiguration
{
param (
[string]$guid
)
$uri = "$MainURL/effectiveMonitoringConfiguration/$guid`?isRecursive=True"
$response = Invoke-WebRequest -Uri $uri -Method GET -WebSession $script:WebSession
return $response.Content | ConvertFrom-Json
}
```

#Data/alertDescription/{alertid}
$alertid="6A88FBC1-0EDC-4173-9BB1-30FFEC296672"
$uri = "$uriBase/data/alertDetails"
$Response = Invoke-WebRequest -Uri "$uriBase/data/alertDetails/$alertid" -Headers $scomheaders -Method Get -WebSession $websession
$Response.Content | Convertto-json
### Script to Execute
Prior to executing the script you will need to uncomment which line you will use for Authentication (lines 4-5, and line 8).
```powershell
# Main Execution

# ------------------------------------------------------------------------------------------
#region Authentication

# Uncomment the below lines if you want to authenticate using specific credentials
# $cred = Get-Credential
# Authenticate-SCOMAPI -Credential $cred

#Criteria: Enter the displayname of the SCOM object
$Criteria = "DisplayName LIKE '%SQL%'"
#Convert our criteria to JSON format
$JSONBody = $Criteria | ConvertTo-Json
$Response = Invoke-WebRequest -Uri "$uriBase/data/class/monitors" -Method Post -Body $JSONBody -WebSession $WebSession
$Response.Content | Convertto-json
# Uncomment the below line if you want to authenticate using the current user's credentials
# Authenticate-SCOMAPI

#endregion
# ------------------------------------------------------------------------------------------

#Data Request in JSON Format
$dashboardbody='
{
"refreshing": false,
"Name": "TestAPIDashboard",
"path": "35b6eba3-6202-8738-a47f-16acf476230f"
}'
$response = Invoke-WebRequest -Uri "$uriBase/monitoring/dashboard" -Headers $scomheaders -Method POST -Body $dashboardbody -ContentType "application/json" -UseDefaultCredentials -WebSession $websession
#Write-Output "-----------------------------------------"

# Replace 'your-guid-here' with the actual GUID of the monitoring object
#$MonitoringObjectGUID = 'your-guid-here'

# Fetch the effective monitoring configuration for the given GUID
#$EffectiveConfig = Get-EffectiveMonitoringConfiguration -guid $MonitoringObjectGUID

# Output the effective monitoring configuration in JSON format
#Write-Output "Effective Monitoring Configuration:`n$($EffectiveConfig | ConvertTo-Json)"

Write-Output "-----------------------------------------"

# Fetch all Windows Servers
Write-Output "Windows Servers:`n"
Get-WindowsServers | ConvertTo-Json

Write-Output "-----------------------------------------"

# Get Unsealed Management Packs
Write-Output "Unsealed MPs:`n"
Get-UnsealedManagementPacks | ConvertTo-Json

Write-Output "-----------------------------------------"

# Get Management Group Health Status
Write-Output "Management Group State:`n"
Get-ManagementGroupState | ConvertTo-Json

Write-Output "-----------------------------------------"
```