如何使用PowerShell通过REST API将CSV文件附加到Service Now事件?

时间:2019-01-30 10:16:13

标签: rest powershell servicenow

我需要使用PowerShell脚本通过SNOW REST API将文件xlsx或CSV附加到特定事件。我尝试了以下代码:

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
}

执行上述脚本时,出现以下错误:

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 个答案:

答案 0 :(得分:0)

尝试将您的内容类型更改为“ 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'
}

错误显示“远程服务器返回错误:(415)不支持 媒体类型。”

可以在此处找到api上的Doco:

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

答案 1 :(得分:0)

您最好的选择是利用ServiceNow中的OOB Attachment API。您将需要通过powershell进行发帖。 Powershell为此Invoke-RestMethodInvoke-WebRequest提供了两个选项。尝试POST时,我最好与后者合作。您可能还需要先在Postman中建立休息电话,以确保可以将附件插入ServiceNow,然后再担心编写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`

答案 2 :(得分:0)

最后我从下面的链接中找到了答案

https://community.servicenow.com/community?id=community_question&sys_id=d3707023dbaceb8023f4a345ca961949及下面的代码:

 # 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