Of late I received a request to share a PowerShell script to download attachment(s) from the given servicenow incident. Two attachments are available for the sample incident INC0010008 below is the illustration.
First we need to query incident by number to retrieve sys_id and through which we get the attachment metadata. Table name incident and table_sys_id are used respectively.
Here is the full code (Change the incident number and credentials)
$IncidentNumber = "INC0010008" $admin = "admin" $password = "admin" | ConvertTo-SecureString -AsPlainText -Force $Credential = New-Object pscredential -ArgumentList ($admin,$password) $Uri = "https://dev42835.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1" $IncidentResult = Invoke-RestMethod -Uri $Uri -Method Get -Credential $Credential if($IncidentResult.result.sys_id -ne $null) { $IncidentAttachments = Invoke-RestMethod -Uri "https://dev42835.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" -Method Get -Credential $Credential $IncidentAttachments.result | Select file_name , download_link } else{ "Incident Not Found!" }
Output is showed below!
file_name download_link --------- ------------- servicenowAttachment.txt https://dev42835.service-now.com/api/now/attachment/5d8d2775db3313006878771ebf961979/file servicenowAttachment1.txt https://dev42835.service-now.com/api/now/attachment/3236ff39db3313006878771ebf96196e/file
Wait! We haven’t downloaded the file right? Here it is!
$IncidentNumber = "INC0010008" $admin = "admin" $password = "admin" | ConvertTo-SecureString -AsPlainText -Force $Credential = New-Object pscredential -ArgumentList ($admin,$password) $Uri = "https://dev42835.service-now.com/api/now/table/incident?sysparm_query=number=$($IncidentNumber)&sysparm_fields=sys_id&sysparm_limit=1" $IncidentResult = Invoke-RestMethod -Uri $Uri -Method Get -Credential $Credential if($IncidentResult.result.sys_id -ne $null) { $IncidentAttachments = Invoke-RestMethod -Uri "https://dev42835.service-now.com/api/now/attachment?sysparm_query=table_sys_id=$($IncidentResult.result.sys_id)" -Method Get -Credential $Credential $Results = $IncidentAttachments.result | Select file_name , download_link foreach($Result in $Results) { Invoke-RestMethod -Uri $($Result.download_link) -Method Get -Credential $Credential -OutFile C:\Temp\Demo\$($Result.file_name) } } else{ "Incident Not Found!" }
Enjoy PowerShell! Here is the reference link for documentation.