The CreatorCon Call for Content is officially open! Get started here.

Powershell - REST - Attachment API - The remote server returned an error: (401) Unauthorized.

bgmoreira
Tera Expert

 

Hi Every body

 

I am creating an update to an attached file using PowerShell to use in a data source that will run weekly.

In the ecc_agent_script_file table, I created this file:

 

Name: ALERTAS-VM.ps1

script:

 

##############################################
##### FILE UPLOAD ALERTAS-VM.csv #####
##############################################


$user = "admin"
$pass = "admin"

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

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json, text/plain, */*')
$headers.Add('Content-Type','application/json')
$headers.Add('X-Transaction-Source','Interface=Web,Interface-Type=Classic Environment,Interface-Name=Unified Navigation App')

 

$recordSysID ="4a6ed75c87547e506be232a70cbb35e0"
$fileName = "ALERTAS-VM.csv"
$instanceName = "xptodev"

 

$uriForFileAttach = "https://$($instanceName).service-now.com/api/now/attachment/file?table_name=$($tableName)&table_sys_id=$($recordSysID)&file_name=$($fileName)"

 

$fileToAttach = "D:\ServiceNow MID Server\agent\work\import_cmdb\vm\ALERTAS-VM.csv"

 

$method = "POST"

 

$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uriForFileAttach -InFile

 

$fileToAttach -ContentType 'multipart/form-data'

 

$response.RawContent

 

I then created a scheduled file to run this PowerShell weekly, as shown in the example below.

 

Example : 

 

var filePath = ' powershell scripts\\ALERTAS-VM.ps1';
var ecc = new GlideRecord('ecc_queue');
ecc.initialize();
ecc.agent = "mid.server." + 'mid_server_0101';
ecc.topic = 'Command';
ecc.name =  filePath;
ecc.queue = 'output';
ecc.state = 'ready';
ecc.source = 'PowerShell';
var payload = '<?xml version="1.0" encoding="UTF-8"?><parameters><parameter name="name" value="' + filePath  + '"/><parameter name="skip_sensor" value="true"/></parameters>';
ecc.payload = payload;
ecc.insert();
gs.info(ecc.sys_id);

 

When I run my script, I always get the following response regardless of who runs it. I've even tested it with the system administrator.

 

Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
No D:\ServiceNow MID Server mid_server_SCELEPAR75974\agent\scripts\CELEPAR-ALERTAS-VM.ps1:33 caractere:13

 

 

Has anyone else had this problem? 

2 ACCEPTED SOLUTIONS

bgmoreira
Tera Expert

For my issue , i resolved with this

 

In my case when a create a new user to user in this powershell command my default password is so long (+- 128 caracters). I changed to a short password (16 caracteres) and the 401 problem is resolved.

 

importante

 

I put this roles to user

 

import_transformer

import_set_loader

import_scheduler

import_admin

 

and flag the option "Internal Integration User" in user register

View solution in original post

I see $tableName and $recordSysID missing in your script. Please add them

I rewrite the script based on Microsoft documentation. Please check whether this works for you

 

$user = "admin"
$pass = "admin"
$recordSysID ="4a6ed75c87547e506be232a70cbb35e0"
$fileName = "ALERTAS-VM.csv"
$instanceName = "xptodev"
$tableName ="<name of the table>"
$recordSysID = "<sys_id of record>"
$fileToAttach = "D:\ServiceNow MID Server\agent\work\import_cmdb\vm\ALERTAS-VM.csv"

# 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/octet-stream')


# Specify endpoint uri
$uri = "https://$($instanceName).service-now.com/api/now/attachment/file?table_name=$($tableName)&table_sys_id=$($recordSysID)&file_name=$($fileName)"

# Specify HTTP method
$method = "post"


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

# Print response
$response.RawContent

Thank you,
Palani

View solution in original post

4 REPLIES 4

palanikumar
Giga Sage
Giga Sage

Are you using the correct credentials?

Make sure these lines are update

$user = "admin" # Update admin with User ID
$pass = "admin" # Update admin with the password

Thank you,
Palani

Hi Palani.

 

Thansk for the help. 

 

This only a example but when a execute the script , i use the correct user and password.

my user contains this roles :

 

admin

import_admin
import_scheduler
import_set_loader
import_transform

I see $tableName and $recordSysID missing in your script. Please add them

I rewrite the script based on Microsoft documentation. Please check whether this works for you

 

$user = "admin"
$pass = "admin"
$recordSysID ="4a6ed75c87547e506be232a70cbb35e0"
$fileName = "ALERTAS-VM.csv"
$instanceName = "xptodev"
$tableName ="<name of the table>"
$recordSysID = "<sys_id of record>"
$fileToAttach = "D:\ServiceNow MID Server\agent\work\import_cmdb\vm\ALERTAS-VM.csv"

# 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/octet-stream')


# Specify endpoint uri
$uri = "https://$($instanceName).service-now.com/api/now/attachment/file?table_name=$($tableName)&table_sys_id=$($recordSysID)&file_name=$($fileName)"

# Specify HTTP method
$method = "post"


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

# Print response
$response.RawContent

Thank you,
Palani

bgmoreira
Tera Expert

For my issue , i resolved with this

 

In my case when a create a new user to user in this powershell command my default password is so long (+- 128 caracters). I changed to a short password (16 caracteres) and the 401 problem is resolved.

 

importante

 

I put this roles to user

 

import_transformer

import_set_loader

import_scheduler

import_admin

 

and flag the option "Internal Integration User" in user register