background script with try catch

CV1
Tera Contributor

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

3 REPLIES 3

Nick Parsons
Mega Sage

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?

CV1
Tera Contributor

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 .

Ankur Bawiskar
Tera Patron
Tera Patron

@CV1 

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.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader