Useful attachment scripts

  • Release version: Yokohama
  • Updated January 30, 2025
  • 2 minutes to read
  • Summarize
    Summarized using AI
    This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.

    Summary of Useful Attachment Scripts

    This content provides a collection of practical attachment-related scripts designed for ServiceNow instances, specifically for the Yokohama release. These scripts enable customers to automate and customize attachment handling, such as copying attachments between records, deleting duplicates, indicating attachment presence in task lists, including attachment links in email notifications, and logging attachment downloads.

    Show full answer Show less

    Important: These scripts are unsupported by Now Support and should be thoroughly tested in your environment before use. Questions and discussions are recommended to be posted in the ServiceNow community forum.

    Key Features

    • Copy Attachments Between Records: Use GlideSysAttachment.copy to duplicate all attachments from one record to another. Note that copying is not selective and copies all attachments.
    • Delete Duplicate Attachments: A script can be run as a business rule, scheduled job, or background script to identify and remove duplicate attachments based on the table and file name to maintain attachment hygiene.
    • Display Attachment Status in Task Lists: Implement a business rule that updates a custom field (uhasattachments) on task records to indicate if attachments exist, enhancing list view visibility of attachment presence. The rule should run after insert or delete operations on attachments.
    • Link Attachments in Email Notifications: Use a script to dynamically generate clickable links to attachments within email templates or notifications, improving user access to related files directly from emails. Replace the placeholder with your ServiceNow instance name.
    • Attachment Download Logging: Attachment download actions trigger attachment.read event records in the event log. These can be processed with Script Actions or Email Notifications to track who downloaded attachments and when, supporting audit and compliance requirements.

    Implementation Notes

    • For the task attachment indicator, a custom boolean field (uhasattachments) must exist on the task table.
    • The attachment copy method copies all attachments without filtering; selective copying requires custom logic.
    • Attachment download logging depends on the current context being a sysattachment record and proper event parameters to capture file and table names.
    • Scripts involving queries and updates use GlideRecord and GlideAggregate APIs standard in ServiceNow, requiring scripting knowledge for customization.

    Benefits for ServiceNow Customers

    • Enhance operational efficiency by automating attachment management tasks.
    • Improve user experience through visibility of attachments directly in task lists and email notifications.
    • Maintain cleaner data by removing duplicate attachments and tracking attachment downloads for audit purposes.
    • Leverage these scripts as templates to build additional attachment-related customizations tailored to your organizational needs.

    This is a searchable version of the Useful Attachment Scripts.

    Warning:
    The customization described here was developed for use in specific instances, and is not supported by Now Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

    Copy attachments from record to record

    Use the following script to copy an attachment from one record to another record:
    GlideSysAttachment.copy('sourcetable','sys_id','destinationtable','sys_id');
    Note:
    GlideSysAttachment.copy copies all attachments; it cannot select specific attachments.

    Delete duplicate attachments

    Use the following script in a business rule, scheduled job, or background script to delete duplicate attachments located in the Attachments [sys_attachment] table:
    function fixDuplicateImages(){
      var now_GR = new GlideRecord('sys_attachment');
      now_GR.addQuery('table_name','LIKE','ZZ_YY%');
      now_GR.orderBy('table_sys_id');
      now_GR.orderByDesc('sys_created_on');
      now_GR.query();
      var lastID ='not_a_match';
      var lastFile ='not_a_match';
      while(now_GR.next()){
        var isDuplicate = (lastID == now_GR.table_sys_id)&&(lastFile == now_GR.file_name);
        lastID = now_GR.table_sys_id;
        lastFile = now_GR.file_name;
        gs.print(now_GR.table_sys_id + ' ' + now_GR.table_name + ' ' + now_GR.file_name + ' ' + now_GR.sys_created_on + ' ' + isDuplicate);
        if(isDuplicate)
          now_GR.deleteRecord();
      }
    }

    Display whether tasks have attachments in list view

    Use the following script in a business rule to display whether tasks have attachments when viewed in the record list view. Note that the script needs a custom field on the Has Attachments [u_has_attachments] table.
    checkAttachment();
     
    function checkAttachment(){
      // if inserting then the task has an attachment
      if(current.operation()=='insert') {
        hasAttachment('true'); // if deleting attachment check for other attachments
        if(current.operation()=='delete') {
          var timeNow3 =new GlideDateTime();
          gs.log('has_attachment br: gliderecord query start date time is: '+ timeNow3.getNumericValue(),'jwtest');
          var attachCount = new GlideAggregate('sys_attachment');
          attachCount.addQuery('table_sys_id',current.sys_id);
          attachCount.addAggregate('COUNT');
          attachCount.query();
          var numAttachments ='0'; 
    
          // if no other attachments task does not have attachment
          if(attachCount.next()){
            numAttachments = attachCount.getAggregate("COUNT");
            if(numAttachments >0){
              hasAttachment ='true';
            } else {
              hasAttachment('false');
            }
            var timeNow4=new GlideDateTime();
            gs.log('has_attachment br: gliderecord query start date time is: '+ timeNow4.getNumericValue(),'jwtest');
          }
     
    function hasAttachment(answer){
      var task = new GlideRecord('task');
      task.addQuery('sys_id',current.table_sys_id);
      task.query();
     
      if(task.next()){
        task.u_has_attachment= answer;
        task.autoSysFields(false);  //Don't set the lastUpdatedTime or the Simultaneous Update Alert will likely get triggered
        task.setWorkflow(false);  //Don't allow other business rules to run, otherwise multiple notifications will likely be sent
        task.update();
      }
    }
    Note:
    Schedule the business rule to run after insert/delete.

    Link to attachments in an email notification

    Use the following script in an email notification or template to include links to attachments:
    
    printattachments(); 
     
    function printattachments(){
      var now_GR =new GlideRecord('sys_attachment');
      now_GR.addQuery('table_sys_id',current.sys_id);
      now_GR.query();
      while(now_GR.next()){
        template.print('Attachment: <a href="http://'+gs.getProperty("instance_name")+'.service-now.com/sys_attachment.do?sys_id='+ now_GR.sys_id+'">'+ now_GR.file_name+'</a>');
      }
    }
    Note:
    Replace "instance_name" with your instance name.

    Attachment Logging

    Whenever a user downloads an attachment, the action writes an attachment.read event record to the event log. If desired, you can process these events with a Script Action or an Email Notification. This can be useful if you want to do something when an attachment is read. For example, you can record when and by whom certain attachments are downloaded. For this functionality, the current variable must point to a sys_attachment record, and the event record must use the following parameters:
    • parm1: File name
    • parm2: Table name