Thursday, September 29, 2022

ServiceNow script to retrieve oAuth token programatically

var instance = 'https://test.service-now.com';

var username = 'testadmin1'; 

var password = 'testadmin1'; 

var clientId = '539decb2e5968b00f5ac882d078e787d'; 

var clientSecret = 'test123'; 

  

// Request a token 

var getTokenRM = new sn_ws.RESTMessageV2(); 

getTokenRM.setEndpoint(instance + '/oauth_token.do'); 

getTokenRM.setHttpMethod("post"); 

getTokenRM.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

getTokenRM.setRequestBody('grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password); 

var responseToken = getTokenRM.execute(); 

gs.print('response..'+ responseToken.getBody());

var token = new JSONParser().parse(responseToken.getBody()); 

Thursday, February 3, 2022

ServiceNow business rule to print the list of columns changed

For Global Scope Applications

 (function executeRule(current, previous /*null when async*/ ) {
    var gru = GlideScriptRecordUtil.get(current);
    var changedFields = gru.getChangedFields();
    var changedFieldNames = gru.getChangedFieldNames();

    //Convert to JavaScript Arrays
    gs.include('j2js');

    changedFields = j2js(changedFields);
    changedFieldNames = j2js(changedFieldNames);

    var arrayLength = changedFields.length;
    gs.log(arrayLength);


    for (var i = 0; i < arrayLength; i++) {
        gs.addErrorMessage(changedFields[i]);
    }

    var arrayLength1 = changedFieldNames.length;
    gs.log(arrayLength);

    for (var i = 0; i < arrayLength1; i++) {
        gs.addErrorMessage(changedFieldNames[i]);
    }
})(current, previous);

For Scoped application tables

 (function executeRule(current, previous /*null when async*/ ) {
    var result = [];
    var elements = current.getElements();
    var size = elements.length;
    for (var i = 0; i < size; i++) {
     var ge = elements[i];
     if (ge.changes()) {
      gs.addErrorMessage(ge.getName());
     }
    }
   })(current, previous);

Monday, January 10, 2022

ServiceNow backend script to wait for a few milliseconds

 function waitForTime(time){  

  var t1 = new GlideDateTime().getNumericValue();  

  var t2 = new GlideDateTime().getNumericValue();  

  var duration = t2 - t1;  

  while(duration < time){  

  t2 = new GlideDateTime().getNumericValue();  

  duration = t2 - t1;  

  }  

}