How to duplicate a GlideRecord on ServiceNow

servicenowWhile working on generating thousand of rows to stress my application on ServiceNow I figure a way to duplicate any GlideRecord.

It’s important to note that in my example I’m querying a table and duplicating each record, this method should work with any single GlideRecord.

For the sake of simplicity here’s the code:

//query the rows we want to copy
var ga = new GlideRecord('cmdb_ci_server');

while ( {
    //get all the fields for this record
    var fields = ga.getFields();
    //create a new record
    var gr = new GlideRecord('cmdb_ci_server');
    for (var i = 0; i < fields.size(); i++) {
        var glideElement = fields.get(i);
        //make sure we don't copy the sys_id
        if(glideElement.getName() != 'sys_id')
            gr[key] = ga.getValue(glideElement.getName());                  
    var newSysId = gr.insert();