Friday, 8 May 2020

Important ServiceNow Script or Reference

ServiceNow Best Practice :




Attachment script Attachment Mandatory --- 




function onSubmit() {

    if (g_form.getValue('non_tracked_devices') == 'Yes') {
        var cat_id = g_form.getValue('sysparm_item_guid');
        var gr = new GlideRecord("sys_attachment");
        gr.addQuery("table_name", "sc_cart_item");
        gr.addQuery("table_sys_id", cat_id);
        gr.query();
        if (!gr.next()) {
            alert("You must add an attachment before submitting this request.");
            return false;
        }
    }

}

//Script to Delete multiple record 

var psc = new GlideRecord('<table_name>'); //Make sure table name is correct
psc.addEncodedQuery('sourceISNOTEMPTY');// Encoded Query or Filter if any required 
psc.addQuery('sourceISNOTEMPTY');//Query or Filter if any required 
psc.setLimit('10'); //Limit number of records 
psc.setWorkflow(false); //Turn off business rule or notifications
psc.deleteMultiple();



//On Change Client script Example ...   Disable or Enable the form 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue == '') {
      return;
   }
    var u1 = g_form.getValue('sitescope_manager'); //optional
g_form.addInfoMessage('Please wait while fetching Server Name');
g_form.getFormElement().disable();
var links = g_form.getFormElement().getElementsByTagName("a");
for ( i=0;i<links.length;i++)
{
links[i].hide();
}
var ga = new GlideAjax('Sitescope');
ga.addParam('sysparm_name','sitescope'); 
ga.addParam('sysparm_sitescope_manager',u1); //optional
ga.getXML(FolderFetch);
}
function FolderFetch(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
if (answer == "start")
{
g_form.showFieldMsg('remote_server_name','There is some Congestion in the Network. Please try again Later','error');
}
else
{
var outputval=answer;
var arr=outputval.split("\n");
var k=0;
while(k!=arr.length)
{
g_form.addOption('remote_server_name', arr[k],arr[k]);
k++;
}
}
g_form.clearMessages();
g_form.getFormElement().enable();
var links1 = g_form.getFormElement().getElementsByTagName("a");
for ( i=0;i<links1.length;i++)
{
links1[i].show();
}
}

   //How to setup OAuth2 authentication for RESTMessageV2 integrations



//Find Duplicate record in table with filed value :

var dupRecords = [];
var gaDupCheck1 = new GlideAggregate('cmdb_ci_hardware');
gaDupCheck1.addAggregate('COUNT', 'serial_number');
gaDupCheck1.groupBy('serial_number');
gaDupCheck1.addHaving('COUNT', '>', 1);
gaDupCheck1.query();
while (gaDupCheck1.next()) {
    dupRecords.push(gaDupCheck1.serial_number.toString());
}
gs.print(dupRecords);


//Script to delete duplicate records: 


var dup = new GlideAggregate('dscy_router_interface');
dup.groupBy('mac_address');
dup.query();
while(dup.next()) {
var dup1 = new GlideRecord('dscy_router_interface');
dup1.addQuery('mac_address', dup.mac_address);
dup1.query();
dup1.next();
while(dup1.next())
dup1.deleteRecord();
}


//CI Asset Synchronization useful scripts 

var serialNum = [”SE415WS47”, ”VMware-42 26 87 93 04 f8 e6 15-9c 43 e6 c2 0e 76 4f 55”,];
for (var i = 0; i < serialNum.length; i++) {
    var grCI = new GlideRecord("cmdb_ci_hardware");
    grCI.addEncodedQuery('sys_class_name=cmdb_ci_computer');
    grCI.addQuery("discovery_source", "MS SMS");
    grCI.addQuery("serial_number", serialNum[i]);
    grCI.query();
    while (grCI.next()) {
        var grAlm = new GlideRecord("alm_hardware");
        grAlm.addQuery("serial_number", serialNum[i]);
        grAlm.query();
        while (grAlm.next()) {
            grAlm.ci = grCI.sys_id.toString();
            grAlm.setWorkflow(false);
            grAlm.update();
        }

    }
}

var serialNum = ["1N44FW2", "1PR8YW2", "1QDKGP2"];
for (var i = 0; i < serialNum.length; i++) {
var grCI = new GlideRecord("cmdb_ci_hardware");
grCI.addEncodedQuery('sys_class_name=cmdb_ci_computer');
grCI.addQuery("discovery_source", "NULL");
grCI.addQuery("serial_number",serialNum[i]);
grCI.query();
while (grCI.next()) {

    var grCI1 = new GlideRecord("cmdb_ci_hardware");
    grCI1.addEncodedQuery('sys_class_name=cmdb_ci_computer');
    grCI1.addQuery("discovery_source", "MS SMS");
    grCI1.addQuery("serial_number", serialNum[i]);
    grCI1.query();
    while (grCI1.next()) {
        grCI1.asset = grCI.asset;
        grCI1.update();

    }
}
}


// Manually Create record in windows Server or any other class using script 

var payload = {
   "items": [
      {
         "className": "u_cmdb_ci_mongoose_web_server",
         "lookup": [],
         "values": {
            "name": "Mongoose@owa-sd-01",            
            "version": “5.5”,
            "running_process_command": "c:\\clouddimensions\\mongoose.exe",
            "sys_class_name": "u_cmdb_ci_mongoose_web_server"
         }
      },
      {
         "className": "cmdb_ci_win_server",
         "lookup": [],
         "values": {
            "name": "OWA-SD-01"
         }
      }
   ],
   "relations": [
      {
         "type": "Runs on::Runs",
         "parent": 0,
         "child": 1
      }
   ]
};

var jsonUtil = new JSON();
var input = jsonUtil.encode(payload);
var output = SNC.IdentificationEngineScriptableApi.createOrUpdateCI(‘ServiceNow’, input);
gs.print(output);


//Azure Fundamental :   -



Remove Middle name from a name in Excel Sheet .

Using formula may be a very easy way for most of Excel users.

Select a blank cell next to the name list, and type this formula =TRIM(LEFT(A1,FIND(" ",LOWER(A1),1))) & " " & TRIM(MID(A1,FIND(" ",LOWER(A1),FIND(" ",LOWER(A1),1)+1)+1,LEN(A1)-FIND(" ",LOWER(A1),1)+1)) into it, then press Enter button on the keyboard and drag the Auto Fill handle to fill the range needed to apply the formula. Now you can see all the name of the list are shown in the new column without middle initials.

// Get all the incidents updated 3 days before

var dupRecords = [];
var count = '';
var gr = new GlideRecord('incident');
gr.addQuery('sys_updated_onRELATIVEGE@dayofweek@ago@3');
gr.query();
while(gr.next()){
dupRecords.push(gr.number);
}
gs.print(dupRecords);

   

ServiceNow Asset Data Load Pre checks or procedure


Pre-Checks
·         Look at the below attribute for data provided in Excel/Data sheet
Acquisition method
Asset tag
Assigned
Assigned to
Comments
Manufacturer
Cost
Cost center
Depreciation
Depreciation effective date
Disposal reason
Due
Installed
 Retired date
State
Invoice number
Managed by
Model
Model Category
Ordered
Purchased
Quantity
Request line
Resale price
Salvage value
Serial number
Stockroom
Substate
DR Option
Part Number
Room
Shared Workstation Reason
Vendor
Warranty expiration
Building
Support group
Beneficiary
Checked in
Checked out
Supported by
Order received
Department
Name
Workstation Classification
Due in
Expenditure type
GL account
Window
Justification
Lease contract
Location
Wave
Owned by
Parent
PO number
Scheduled retirement
Reserved for



·         Check for all the reference or choice field value is available in ServiceNow or Now
o   Assigned To
o   Supported By
o   Support Group
o   State
o   Sub State
o   Manufacturer
o   Model Category
o   Model
o   Location
o   DR Option
o   Name (Configuration Item)
·         Confirm that if any of the above attribute value is not available in ServiceNow, Should you create new value of it or not.
·         When you have proper data in hand start loading the data into ServiceNow using below steps
o   Create a Data load
§  System Import Set à Load Data
§  Create new Staging table to load the data
o   Create Transform Map
§  Map all the attribute from Source Table (Newly created Staging table) to target table (alm_hardware or alm_asset)
§  Select coalesces field to remove duplication
§  Select choice action properly
§  Create a transform map script if required
·         On Start
·         On Complete
·         On Before
·         On After
·         On choice Create
·         On Reject etc.
o   Run the data load
§  Select the transform map created above.

Transform used to load data in LYB ServiceNow


Post-Checks
·         Check for the below attribute whether data loaded properly or now.
o   Assigned To
o   Supported By
o   Support Group
o   State
o   Sub State
o   Manufacturer
o   Model Category
o   Model
o   Location
o   DR Option
o   Name (Configuration Item)
·         Check for the below table whether any unnecessary value created because of data load
o   User
o   Group
o   Location
o   Hardware CI
o   State Choice
o   Substate Choice etc.
·         Run Below script on alm_hardware and cmdb_ci_hardware table for duplicate CI using Serial Number

var dupRecords = [];
var gaDupCheck1 = new GlideAggregate('cmdb_ci_hardware');
gaDupCheck1.addAggregate('COUNT', 'serial_number');
gaDupCheck1.groupBy('serial_number');
gaDupCheck1.addHaving('COUNT', '>', 1);
gaDupCheck1.query();
while (gaDupCheck1.next()) {
               
    dupRecords.push(gaDupCheck1.serial_number.toString());
}
gs.print(dupRecords);

·         Delete all duplicate value created because of transform map.
·         If required use below script to delete duplicate value :  ( Run with high precautions)

var dup = new GlideAggregate(‘alm_hardware’);
dup.groupBy('serial_number');
dup.query();
while(dup.next()) {
                var dup1 = new GlideRecord('alm_ hardware’');
                dup1.addQuery('serial_number', dup.serial_number);
                dup1.query();
                dup1.next();
                while(dup1.next())
                                dup1.deleteRecord();
}
Further Reference for Data load or transform Maps.