0
votes

I need to attach the file either xlsx or CSV to a particular incident via SNOW REST API using PowerShell script. I have tried with the below code:

if (!$script:ServiceNowCreds) {
    $script:ServiceNowCreds = Get-Credential
}
$snow_url = 'https://dev652xx.service-now.com/api/now/table/incident'
$Body = @{
    'number' = 'INC00xx059'    
}
$result = Invoke-RestMethod -Uri  $snow_url -Credential $script:ServiceNowCreds -Body $Body -ContentType "application/json" 
$result.result | select sys_id, number | ForEach-Object {
    $Upload_snow_url ='https://dev652xx.servicenow.com/api/now/attachment/upload'
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add('Content-Type','text/csv')
    $headers.Add('Accept','*/*')
    $sys_id = $_.sys_id
    $incident_number = $_.number
    $UploadBody = @{
        'table_name'='incident'; 
        'table_sys_id'=$sys_id;
        'file_name' = 'C:\Users\suganthanraj.p\Documents\Servers.csv'
    }
    $uploadParam = $UploadBody | ConvertTo-JSon
    Write-Host $sys_id
    Write-Host $incident_number
    $UploadResult = Invoke-RestMethod -Uri $Upload_snow_url -Credential $script:ServiceNowCreds -Body $uploadParam -Method Post -Headers $headers
    $UploadResult
}

When I execute the above script I am getting the below error:

Invoke-RestMethod : The remote server returned an error: (415) Unsupported 
Media Type.
At C:\Users\suganthanraj.p\Desktop\SNOW-UploadAttachment.ps1:39 char:21
+ ... oadResult = Invoke-RestMethod -Uri  $Upload_snow_url -Credential $scr ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
3

3 Answers

0
votes

Try changing you content type to "multipart/form-data"

$headers.Add('Content-Type','multipart/form-data')

$UploadBody = @{
    'table_name'='incident'; 
    'record_sys_id'=$sys_id;
    'uploadFile' = 'C:\Users\suganthanraj.p\Documents\Servers.csv'
}

The error says "The remote server returned an error: (415) Unsupported Media Type."

Doco on the api can be found here:

https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_AttachmentAPI-POSTmultipart.html

0
votes

Your best option would be leverage the OOB Attachment API in ServiceNow. You will need to make a post call from powershell. Powershell has two options for this Invoke-RestMethod and Invoke-WebRequest. I have had better luck with the latter when trying to POST. You might also first build your rest call in Postman make sure you can get the attachment into ServiceNow, then worry about writing your PS.

$Body = @{
User = 'jdoe'
password = 'P@S$w0rd!'
}
$LoginResponse = Invoke-WebRequest 'http://www.contoso.com/login/' - SessionVariable 'Session' -Body $Body -Method 'POST'

$Session
$ProfileResponse = Invoke-WebRequest 'http://www.contoso.com/profile/' -`WebSession $Session $ProfileResponse`
0
votes

Finally i found answer from the below link

https://community.servicenow.com/community?id=community_question&sys_id=d3707023dbaceb8023f4a345ca961949 and below is the code:

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

 # 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://dev652XX.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=850XXXXX2200e0ef563dbb9a71c1&file_name=TreeSizeReport.csv"

# Specifiy file to attach
$fileToAttach = "C:\Users\suganthanraj.p\Desktop\TreeSizeReport.csv"

# Specify HTTP method (POST, PATCH, PUT)
$method = "POST"

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

# Print response
$response.RawContent