Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Copy value from one field to another field based on a condition using Fix Script

Owais3
Tera Expert

Hello Devs,

 

I've got a Fix Script which only updates the limit amount once, and then when I re-run it nothing updates. Below is the script which partially works or so to say only works once.

 

(function() {
    // Creating a GlideRecord for the 'cmdb_ci' table
    var gr = new GlideRecord('cmdb_ci');
    // Querying CMDB CI records where 'owned_by' is not empty
    gr.addNotNullQuery('owned_by');
    // Limiting the query to 10 records
    gr.setLimit(10);
    // Executing the query
    gr.query();
    // Looping through the records and updating 'assignment_group' based on 'owned_by'
    while (gr.next()) {
        gr.assignment_group = gr.owned_by;
        gr.update();
    }
    gs.info('Fix script completed successfully. Updated 10 records.');
})();

 

Any idea?... Has to be a Fix Script.

Thanks

1 ACCEPTED SOLUTION

OlaN
Tera Sage
Tera Sage

Hi,

Try something like this (worked fine for me).

 

var copyCmdbResult = copyValues();
if (copyCmdbResult == 0){
	gs.info('No records updated');
}
else{
	gs.info('Update finished, Updated ' + copyCmdbResult + ' records');
}

function copyValues() {
	var cmdbGR = new GlideRecord('cmdb_ci');
	cmdbGR.setLimit(3);
	cmdbGR.addNotNullQuery('owned_by');
	cmdbGR.addNullQuery('assigned_to'); // added to make sure we don't overwrite existing value
	cmdbGR.query();
	var counter = 0;
	while (cmdbGR.next()){
	//    gs.info('id: ' + cmdbGR.getUniqueValue());
		cmdbGR.setValue('assigned_to', cmdbGR.getValue('owned_by')); // used getters and setters
		cmdbGR.update();
		counter++;
	}

	return counter;
}

 

View solution in original post

5 REPLIES 5

OlaN
Tera Sage
Tera Sage

Hi,

Try something like this (worked fine for me).

 

var copyCmdbResult = copyValues();
if (copyCmdbResult == 0){
	gs.info('No records updated');
}
else{
	gs.info('Update finished, Updated ' + copyCmdbResult + ' records');
}

function copyValues() {
	var cmdbGR = new GlideRecord('cmdb_ci');
	cmdbGR.setLimit(3);
	cmdbGR.addNotNullQuery('owned_by');
	cmdbGR.addNullQuery('assigned_to'); // added to make sure we don't overwrite existing value
	cmdbGR.query();
	var counter = 0;
	while (cmdbGR.next()){
	//    gs.info('id: ' + cmdbGR.getUniqueValue());
		cmdbGR.setValue('assigned_to', cmdbGR.getValue('owned_by')); // used getters and setters
		cmdbGR.update();
		counter++;
	}

	return counter;
}