Automatically Delete Attachments
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-24-2024 10:02 PM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-24-2024 10:19 PM - edited 07-24-2024 10:23 PM
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.
If my answer solves your issue, please mark it as Accepted & Helpful!