Correct SYNTAX to create an event using the REST API and a POWERSHELL script

dirkvanloon
Tera Contributor

Hi,

I am trying to create events using the REST API and Powershell

It works fine using the REST API explorer, but when I try to use the generated script it fails.

After tweaking it I get events with the status "error".

$body = \"source\":\"rest api explorer\"

Does anyone have the correct syntax for the above line?

Regards,

Dirk

4 REPLIES 4

mamann
Mega Guru

I'm not sure if I completely understand what you're trying to accomplish. If it's trying to invoke a REST API from a Powershell script, you can use the code below.



Invoke-RestMethod -Uri "<YOUR REST ENDPOINT>" -Method Post -Credential $cred -Body $json -ContentType "application/json"


Hi Mark,



Thanks for your feedback.


Let me get a bit more into detail:


I am trying to generate an event in the em_event table using the generated script from the REST API explorer. (see below)



The difficult part is the content of the body: I don't know what the correct syntax is. And I have never user powershell or the REST API before.



Kind regards,



# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "admin"


# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))


# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','application/json')


# Specify endpoint uri
$uri = "
https://*************.service-now.com/api/now/table/em_event"


# Specify HTTP method
$method = "post"


# Specify request body
{request.body ? "$body = \"" :""}}{\"source\":\"rest api explorer\",\"description\":\"testing rest\",\"node\":\"Server1\",\"resource\":\"diskspace\",\"message_key\":\"low diskspace\",\"severity\":\"Major\",\"type\":\"warning\",\"alert\":\"\"}"


# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $body


# Print response
$response.RawContent


Hi Dirk, did you find a solution?



I have the same problem. The Powershell coming out of the REST explorer has a syntax error in the "request.body" part.


(unless they expect you to put something into the statement, which they could point out 🙂 )



Kind regards


Flemming


Assuming you are using Powershell 7+ and Oauth2 credentials

 

function Get-OAuthToken {
        param (
            [string]$myenv,
            [string]$clientid,
            [string]$clientsecret,
            [string]$username,
            [string]$password
        )
   
        $RestEndpoint = "https://$($myenv).service-now.com/oauth_token.do"
        $restbody = @{
            'grant_type' = 'password'
            'client_id' = $clientid
            'client_secret' = $clientsecret
            'username' = $username
            'password' = $password
        }
   
        write-host "Contacting $($RestEndpoint) for Oauth token"
        $result = Invoke-RestMethod -Uri $RestEndpoint -Body $restbody -Method Post
        if ($result) {
            $global:oauth_response = $result # We will use global variable $oauth_response for it to be available outside script
            $global:authheaders = @{
                Authorization = "Bearer $($global:oauth_response.access_token)"
            }
         write-host 'Token response was saved to $oauth_response and authorization headers to $authheaders'
        }
    }
function Create-ServiceNowSingleEvent {
        param (
            [string]$myenv,
            [array]$events,
            [string]$token
        )
   
        # Define the API endpoint for creating events
        $apiUrl = "https://$myenv.service-now.com/api/now/table/em_event"
   
        # Convert events data to JSON
        $jsonData = $events | ConvertTo-Json
   
        # Create the headers for the API request
        $headers = @{
            Authorization = "Bearer $token"
            "Content-Type" = "application/json"
        }
   
        # Make the API request to create the events
        $response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $jsonData -Headers $headers
   
        # Output the response
        return $response
    }
$myenv = "companystage" #constellationstage.service-now.com
$clientid = 'IDSTRIN'
$clientsecret = 'soVerySecret'
$username = 'JamesBond'
$password = 'giantSecurePassword'
 
######Example of event structure: ##############################
$events = @(
    @{
        "source" = "PowerShell Script"
        "node" = "Server01"
        "type" = "Error"
        "severity" = "Critical"
        "description" = "Sample event 1 created via PowerShell"
    },
    @{
        "source" = "PowerShell Script"
        "node" = "Server02"
        "type" = "Warning"
        "severity" = "High"
        "description" = "Sample event 2 created via PowerShell"
    },
    @{
        "source" = "PowerShell Script"
        "node" = "Server03"
        "type" = "Info"
        "severity" = "Low"
        "description" = "Sample event 3 created via PowerShell"
    }
)
############################################
Get-OAuthToken -myenv $myenv -clientid $clientid -clientsecret $clientsecret -username $username -password $password
 
Create-ServiceNowSingleEvent -myenv $myenv -events $events -token $global:oauth_response.access_token