T

his script was designed specifically for easily creating a copy of a variable set but it could be easily adapted to create a copy of any other record (and associated records) in ServiceNow. Rather than use a field-by-field copy technique, this script works more like an ‘insert’ on the records it touches. Because of this, you get an exact copy without having to specify each and every field to copy. If you don’t want an exact copy of a particular field, you can overwrite it in the script. You can implement this copy functionality to copy a variable set by creating a UI action with the following settings…

Copy Set UI Action
Name: Copy Set
Table: Variable Set (item_option_new_set)
Action name: copy_set
Form button: True
Script:

//Make sure current changes are saved...
current.update();

//Copy the variable set
copyVS();
function copyVS() {
//Get the current sys_id value for querying
var vsID = current.sys_id.toString();
//Initialize new variable set for insertion
var newVS = current;
//Override the variable set name with a new name
newVS.name = current.name + ' (COPY)';
current.insert();

//Copy associated variables and client scripts
copyVar(vsID);
copyCS(vsID);
gs.addInfoMessage('Variable set ' + newVS.name + ' created.');
action.setRedirectURL(newVS);
}
function copyVar(vsID) {
//Copy the associated variables
var vars = new GlideRecord('item_option_new');
vars.addQuery('variable_set', vsID);
vars.query();
while(vars.next()){
//Get the current sys_id value for querying
var varID = vars.sys_id.toString();
var newVar = vars;
newVar.variable_set = current.sys_id;
vars.insert();
copyChoice(varID, newVar.sys_id.toString());
}
}
function copyCS(vsID) {
//Copy the associated catalog client scripts
var scripts = new GlideRecord('catalog_script_client');
scripts.addQuery('variable_set', vsID);
scripts.query();
while(scripts.next()){
var newCS = scripts;
newCS.variable_set = current.sys_id;
scripts.insert();
}
}
function copyChoice(varID, newVarID) {
//Copy the associated question choices for choice variables
var choices = new GlideRecord('question_choice');
choices.addQuery('question', varID);
choices.query();
while(choices.next()){
var newChoice = choices;
newChoice.question = newVarID;
choices.insert();
}
}