John Zhang1
Kilo Patron
Kilo Patron

Introduction

ServiceNow recommends to avoid using hard-coded values in scripts, as they can lead to unpredictable results and can be difficult to track down later as well as they may not be the same between instances. As a solution, ServiceNow recommend two ways:

a.  try looking up a value by reference 

b. by creating a property and retrieving the value with gs.getProperty().

 

The purpose of this blog is to show you how to identify the hard-coded values for sysID in scripts and what the best script can be used to fix this issue.

 

Identify Hard code SysId using system scan

We can use ServiceNow system scan to check on had code within a script using the instance scan feature.  There are four options we can use (see below).  

JohnZhang1_2-1689716929688.png

You can use following script to perform table scan for both client side or server side script scanning. 

JohnZhang1_0-1689716841813.png

 

Identify Hard code SysId using the script

You can use the following script run in "Script - Background" to scan any type of script after you specify tablename variable.

 

//Check business rule table
var tableName = "sys_script";
identifyHardCode(tableName);

function identifyHardCode(tableName){
//Since sysID is 32 characters so use the following to match any string made of 32 hexadecimal characters
var regexp = /[0-9a-f]{32}/;

var gr = new GlideRecord(tableName);
gr.query();

while (gr.next()) {

if (gr.script.match(regexp))
gs.print('Sys_id found in script: ' + gr.name);

}}

 

Results blow:

JohnZhang1_0-1689464032006.png

 

Client Side script solution

After you identify the hard code resource, you can address them by using gs.getProperty() to replace hard code sysID recommended by ServiceNow,  but gs.getProperty() can only be used in the Server script so Ajax approach can be used for the client side of script.

 

  • The client side script solution:

Script Include:

Create Script Include to process gs.getProperty() and use client script's AJAX to get the value from the defined script.

JohnZhang1_0-1689636151409.png

Catalog Client Script:

JohnZhang1_1-1689636310638.png

  • Server  Script Solution

You can use gs.getProperty()  directly in the server scripts to replace any hard code for sysID.  I am not going to provide samples here because you can simply apply. 

 

  1. Reference

JohnZhang1_0-1690041681915.png

 

3 Comments