background script with try catch
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎04-13-2025 12:01 PM - edited ‎04-13-2025 07:17 PM
Hi All,
We have a requirement to copy value of field4 to field 2 for a list of records from a table and update (not all records of the table should be updated. there are duplicates for field 4. Looking for background script with try - catch where it will add all the error records to the variable and continue to update other records that we have in encodedquery.)
TIA
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎04-13-2025 05:21 PM
What code have you written so far and what specifically isn't working with your attempt? Also what's the purpose of needing a try-catch here, what runtime errors are you expecting to be thrown that you want to be caught?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎04-13-2025 07:17 PM
Basically looking for a background script to copy one field value to another for a given list of records and skip duplicate records and store them in an array to investigate .
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎04-13-2025 08:54 PM
try this but please enhance as we don't know the exact details
(function() {
var tableName = 'your_table_name'; // Replace with your table name
var encodedQuery = 'your_encoded_query'; // Replace with your encoded query
var errorRecords = [];
var gr = new GlideRecord(tableName);
gr.addEncodedQuery(encodedQuery);
gr.query();
while (gr.next()) {
try {
if (gr.field4) {
gr.field2 = gr.field4;
gr.update();
}
} catch (e) {
errorRecords.push(gr.sys_id.toString());
}
}
if (errorRecords.length > 0) {
gs.info('Error updating records: ' + errorRecords.join(', '));
} else {
gs.info('All records updated successfully.');
}
})();
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader