Created
March 22, 2024 22:50
-
-
Save asimpkin/a799bfd9d2f4af397bc626bad21ea33e to your computer and use it in GitHub Desktop.
ServiceNow background script to export multiple tables and append to a task as an .XML attachment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run in background here: now/nav/ui/classic/params/target/sys.scripts.do | |
// started from: https://www.servicenow.com/community/developer-forum/use-script-to-export-records-to-xml/m-p/2571773 | |
// all credit to Riya Verma: https://www.servicenow.com/community/user/viewprofilepage/user-id/199367 | |
// This will NOT get any attachments for the record. | |
// Define the tables you want to export records from | |
var tablesToExport = ['rm_epic', 'rm_story']; | |
// var tablesToExport = ['rm_epic']; // test with one table | |
// Loop through each table | |
for (var i = 0; i < tablesToExport.length; i++) { | |
var tableName = tablesToExport[i]; | |
// Query records from the table | |
var gr = new GlideRecord(tableName); | |
gr.query(); | |
// Create XML document | |
var xmlDoc = new XMLDocument(); | |
xmlDoc.createElement(tableName + 's'); // Root element | |
// Loop through the records | |
while (gr.next()) { | |
var recordNode = xmlDoc.createElement(tableName); | |
// Add fields as child elements | |
var fields = gr.getFields(); | |
for (var j = 0; j < fields.size(); j++) { | |
var field = fields.get(j); | |
var fieldName = field.getName(); | |
var fieldValue = gr.getValue(fieldName); | |
var fieldNode = xmlDoc.createElement(fieldName); | |
fieldNode.setTextContent(fieldValue); | |
recordNode.appendChild(fieldNode); | |
} // end for | |
xmlDoc.appendChild(recordNode); | |
} // end while | |
} // end for each table | |
// set all the XML to a var and write to a file in a task | |
var xmlContent = xmlDoc.toString(); | |
var fileDateTime = new GlideDateTime(); | |
//attach the xmlContebnt as a file to a record. | |
var grRec = new GlideRecord("rm_story"); // table of the record you want to write to | |
grRec.addQuery("sys_id","835b3e76dbca755049b3ae19139619ee"); // sys_id of the record you want to attache the file to | |
grRec.query(); | |
if(grRec.next()){ | |
var grAttachment = new GlideSysAttachment(); | |
grAttachment.write(grRec, 'Agile_Backup - ' + fileDateTime + '.xml', 'application/xml',xmlContent); | |
} // end if next record | |
// Log the export details | |
gs.info('Exported ' + gr.getRowCount() + ' records from ' + tableName + ' to .XML '); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modded a few lines from the org to date the file.