Skip to content

Instantly share code, notes, and snippets.

@d-oderbolz
Created November 13, 2017 11:31
Show Gist options
  • Save d-oderbolz/148d6a79633c4f637ae5174c7d8e9ebd to your computer and use it in GitHub Desktop.
Save d-oderbolz/148d6a79633c4f637ae5174c7d8e9ebd to your computer and use it in GitHub Desktop.
// This is a gist to show how NOT to write a Service Now Script Include to return an array with
// the results of a query
// As an example, I use the sys_properties table, but of course, any table will do (AKA: not work)
var Toolbox_Functions = Class.create();
Toolbox_Functions.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getPropertyList: function (prefix)
{
// 06.11.2017 - Return a list of System Properties whose name starts with prefix
try {
var arr = [];
var property_gr = new GlideRecord('sys_properties');
property_gr.addQuery('name', 'STARTSWITH', prefix);
property_gr.query();
while (property_gr.next())
{
// Push new value onto array.
// THIS IS THE CRITICAL LINE (WRONG!)
arr.push(property_gr.name);
}
return arr;
}
catch(err)
{
gs.eventQueue("script.error", "", "ERROR: PSI_Toolbox_Functions.getPropertyList", err + " in line:" + err.lineNumber);
}
}
};
@d-oderbolz
Copy link
Author

d-oderbolz commented Nov 13, 2017

If you run this, you will be surprised.
As an example, I created these 3 properties:

  • sc.firewall.notify.1
  • sc.firewall.notify.2
  • sc.firewall.notify.3

var Toolbox = new Toolbox_Functions()

var res= Toolbox.getPropertyList("sc.firewall.notify.")
gs.print(res);

[0:00:00.002] Script completed in scope global: script
*** Script: sc.firewall.notify.3,sc.firewall.notify.3,sc.firewall.notify.3

Whoa what's that?
The problem is that property_gr.name (line 23) contains an object reference and it will always point to the last element read (that is why we get the third entry three times)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment