Automatically Delete Attachments

ellisonath
Tera Contributor

Hi there,

 

I've been browsing the community and documentation for some mechanism to use that will automatically delete attachments from the sys_attachment table (along with the associated data in sys_attachment_doc) after a given period of time (and with conditions), but have been unable to find anything suitable. So far I've examined the following options:

 

- Table Cleaner (sys_auto_flush) - this doesn't allow selection of sys_attachment as the target table to clean
- Table rotation - doesn't allow the specification of conditions for deletion

 

Does anyone know if there is an out-of-the-box solution for automatically removing attachments from an instance, or is a custom (possibly scripted) solution required?

 

Many thanks

Nathan

 

1 REPLY 1

Vrushali  Kolte
Mega Sage

Hello @ellisonath ,

 

To achieve this requirement, you can make use of scheduled Script Execution. Scheduled Script Executions in ServiceNow are used to run scripts at defined intervals. These scripts can be used for a variety of tasks, such as data cleanup, automated reporting, and maintenance tasks.

 

below is the sample code -

(function() {
    // Set the conditions for deleting attachments
    var daysOld = 30; // Number of days after which attachments should be deleted
    var deleteBeforeDate = new GlideDateTime();
    deleteBeforeDate.addDaysUTC(-daysOld);

    // Query to find attachments older than the specified number of days
    var attachmentGR = new GlideRecord('sys_attachment');
    attachmentGR.addEncodedQuery('sys_created_on<' + deleteBeforeDate);
    attachmentGR.query();

    while (attachmentGR.next()) {
        // Delete the attachment document first
        var attachmentDocGR = new GlideRecord('sys_attachment_doc');
        attachmentDocGR.addQuery('sys_attachment', attachmentGR.sys_id);
        attachmentDocGR.query();
        while (attachmentDocGR.next()) {
            attachmentDocGR.deleteRecord();
        }

        // Delete the attachment
        attachmentGR.deleteRecord();
    }
})();

Let me know if you need any help in the scripting.

 

Below links will give you a good idea on what is schedule script and how to configure it.

https://developer.servicenow.com/dev.do#!/learn/learning-plans/utah/new_to_servicenow/app_store_lear...

https://developer.servicenow.com/dev.do#!/learn/courses/washingtondc/app_store_learnv2_automatingapp...

 

If my answer solves your issue, please mark it as Accepted & Helpful!