Search code examples
powershellsoapservicenowinvoke-command

POSTing data to ServiceNow via Powershell using Invoke-WebRequest


I am trying to POST information into a table in ServiceNow via a Powershell script. When I run it I get an error

Invoke-WebRequest : The remote server returned an error: (500) Internal Server Error.

Can someone help me figure out how to solve this? Thank you all in advance.

$userName = 'helpMe'
$password = 'iAmStuck' | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $password)
$uri = 'stuff'
$postParams = "test"
#[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Invoke-WebRequest -Uri $uri -Method Post -Body $postParams -Credential $cred 

Solution

  • ServiceNow has a REST API explorer with various code examples to start working with.

    Below is an example that I threw together that posts to the incident table with an admin account. Two important factors here, the user must have roles (here for info https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/integrate/inbound-rest/reference/r_RESTAPIRoles.html) to use the API and must have access to the table you are trying to post to. Also, note that the body of the post needs to be RAW JSON and all the correct header data is supplied in the URL. If successful ServiceNow will return JSON data about the post.

    # Eg. User name="admin", Password="admin" for this code sample.
    $user = "admin"
    $pass = "noPassword"
    
    # 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://xxxxx.service-now.com/api/now/table/incident"
    
    # Specify HTTP method
    $method = "post"
    
    # Specify request body
    {request.body ? "$body = \"" :""}}{\"active\":\"true\",\"number\":\"123\",\"short_description\":\"test\"}"
    
    # Send HTTP request
    $response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $body
    
    # Print response
    $response.RawContent