Copy attachment from Change Task to Change Request via sys_attachment table

Rahil Mirza
Tera Contributor

Hi,

I am trying to copy attachments from ctask to change, I am able to do it but I am getting duplicates of previously attached attachments on change request level as I add any new attachment,

Here is the BR script:

(function executeRule(current, previous /*null when async*/) {
// Get the Change Task record associated with the attachment
var changeTaskGr = new GlideRecord('change_task');
if (changeTaskGr.get(current.table_sys_id)) {
// Get the parent Change Request Sys ID from the Change Task record
var changeRequestSysId = changeTaskGr.getValue('parent');

// Check if an attachment with the same name and file size already exists in the Change Request
var attachmentName = current.file_name.toString();
var attachmentSize = current.size_bytes.toString();
var targetAttachments = new GlideSysAttachment().getAttachments('change_request', changeRequestSysId);
var exists = false;

while (targetAttachments.next()) {
if (targetAttachments.file_name.toString() === attachmentName &&
targetAttachments.size_bytes.toString() === attachmentSize) {
exists = true;
break;
}
}

// Copy the attachment if it does not already exist
if (!exists) {
GlideSysAttachment.copy(current.table_name, current.table_sys_id, 'change_request', changeRequestSysId);
// Log the action for debugging purposes
gs.log('Copied attachment from change_task: ' + current.sys_id.toString() + ' to change_request: ' + changeRequestSysId);
} else {
gs.log('Attachment already exists in change_request: ' + changeRequestSysId);
}
}
})(current, previous);

9 REPLIES 9

@Rahil Mirza 

Did my response help?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

@Rahil Mirza 

Hope you are doing good.

Did my reply answer your question?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi @Ankur Bawiskar , As per your response 
1) If we delete the previous ones and copy only the fresh, the other attachments on change which are not related to the ctask will also delete
2nd and 3rd will copy only a single record, with file name, that is also not feasible

Please let me know your thoughts on this.

@Rahil Mirza 

for the 1st time copy all files.

From next time onwards only copy single file

What's the trigger condition for that BR to copy file to ctask?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

BR condition is After Insert on sys_attachment table.

Thanks,
Rahil