CSM 10.2.2 Documentation

Home

PowerShell Example: Perform an Ad-hoc Search with Sorting

The following example shows how to perform an ad-hoc search for Incidents sorted in ascending order.

                        # Set server login variables
$serverName = "your server"
$apiKey = "your client id"
$userName = "CSDAdmin"
$password = "CSDAdmin"
$baseUri = "http://${serverName}/CherwellAPI/"

# Get an access token
$tokenUri = $baseUri + "token"
$authMode = "Internal"
$tokenRequestBody =
@{
    "Accept" = "application/json";
    "grant_type" = "password";
    "client_id" = $apiKey;
    "username" = $userName;
    "password"= $password
}
$tokenResponse = Invoke-RestMethod -Method POST -Uri "${tokenUri}?auth_mode=${authMode}&api_key=${apiKey}" -Body $tokenRequestBody

$requestHeader = @{ Authorization = "Bearer $($tokenResponse.access_token)" }

# Get the business object summary for Incident. This will give us the busObId
$summaryUri = $baseUri + "api/V1/getbusinessobjectsummary/busobname/Incident"
$summaryResponse = Invoke-RestMethod -Method GET -Uri $summaryUri -ContentType application/json -Header $requestHeader
$busObId = $summaryResponse[0].busobId

# Get the business object schema for Incident. We need this to get the field id for Status
$schemaUri = $baseUri + "api/V1/getbusinessobjectschema/busobid/" + $busobId
$schemaResponse = Invoke-RestMethod -Method GET -Uri $schemaUri -ContentType application/json -Header $requestHeader
$statusField = $schemaResponse.fieldDefinitions | Where-Object {$_.name -eq "Status"}

# Put together the request
$searchResultsRequest =
@{
    BusObId = $busObId;
    PageSize = 200;
    Sorting = @(
        @{
            fieldId = $statusField.fieldId;
            sortDirection = 1
        })
} | ConvertTo-Json

# Run the search
$searchUri = $baseUri + "api/V1/getsearchresults"
$searchResultsResponse = Invoke-RestMethod -Method POST -Uri $searchUri -ContentType application/json -Header $requestHeader -Body $searchResultsRequest
                    

Was this article useful?