Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Blog: How to use the Attachment API in Powershell

mugi-san
Tera Guru

Hi, Everyone.

 

If you want to transfer data to ServiceNow, you might have considered sending a local file from your Windows PC or Server via the API. Of course, you would probably limit your use of this API and run it from a PC or server located on a secure internal network.

Unfortunately, there doesn't seem to be a role that has access to just the sys_attachment table, so I came up with an implementation that allows users granted "sn_request_write" permission to still attach records to "sc_req_item".

 

In this example, we submitted a CSV file.

To ensure ServiceNow handles it correctly, please note that the CSV file must be saved in UTF-8 format without BOM.(If you might think to use this file for import)

 

Note: glide.rest.max_content_length [sys_properties] (defaulted at 10 MB, max 25 MB) 
https://www.servicenow.com/docs/ja-JP/bundle/xanadu-api-reference/page/integrate/custom-web-services...

 

I hope this test helps someone.

 

regards.

 

If you found this post helpful, I would appreciate it if you could click the “Good” button.

 

(This is just a test post, as blog posts might not seem to be popular with the community.

If there's no need for it, I'll use other media to post my test results in the future.)

 

 

mugisan_0-1764751083495.png

 

FileUploader.ps1

# ServiceNow Instance details
$ServiceNowInstance = "devxxxxxx.service-now.com"
$ServiceNowUser = "hogehoge"
$ServiceNowPassword = "What1sy0uRN@me"

# Attachment details
$Table = "sc_req_item"
$RecordSysId = "74b290da4769761084ef9d74116d4395"
$FilePath = "C:\Users\xxxxx\power\Sample.csv"
$Date = Get-Date -Format "yyyyMMdd"
$FileName = "$Date" + "_Sample.csv"

# Construct the URI
$Uri = "https://$ServiceNowInstance/api/now/attachment/file?table_name=$Table&table_sys_id=$RecordSysId&file_name=$FileName"

# Create headers for authentication
$Headers = @{
    Authorization = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($ServiceNowUser):$($ServiceNowPassword)"))
}

# Read file content into a byte array
$FileContent = [System.IO.File]::ReadAllBytes($FilePath)

try {
    # Make the POST request
    $Response = Invoke-RestMethod -Uri $Uri -Method Post -Headers $Headers -Body $FileContent -ContentType "application/octet-stream"

    Write-Host "Attachment uploaded"
    $Response | Format-List
}
catch {
    Write-Error "Attachment uploaded Error: $($_.Exception.Message)"
}

 

 

0 REPLIES 0