Job Switch Kit: Everything you need to crack your next ServiceNow interview Get Job Switch Kit →
Get the complete ServiceNow interview prep system — 500+ Q&A, mock interviews & more Get Job Switch Kit →

ServiceNow Scripting Scenario Based Interview Questions 2026

How the scripting round usually works: the interviewer asks you to share your screen and write the script live, either in your own PDI (Personal Developer Instance), usually in Scripts - Background, or in a plain notepad or shared document. They watch how you approach the problem as much as the final script, so explain your thinking as you type.

Before the interview: be ready for both. Log in to your PDI an hour early: a PDI goes to sleep when it isn't used, and waking it up can take several minutes you won't have during the call. For a notepad round there is no autocomplete and no way to run the script, so practise writing the common GlideRecord and GlideAggregate patterns from memory.

Best practices interviewers look for:

  • Meaningful variable names. Use incidentGr or activeUsers, not gr. A generic gr can also clash with other scripts running in the same scope.
  • Filter in the query, not in the loop. Put every condition in addQuery(), or copy the filter from a list (right-click the breadcrumb, Copy query) and use one addEncodedQuery().
  • Never query inside a loop. Dot-walk (caller_id.email) or collect the sys_ids and query once.
  • Count with GlideAggregate, not by looping a GlideRecord or calling getRowCount().
  • Use getValue() and setValue() instead of reading fields directly, so you work with plain strings, not field objects.
  • Be careful with bulk updates. Try the query on a few records with setLimit() first, and decide whether Business Rules and notifications should run (setWorkflow(false)).

New: practise these scripts right here

Each scenario below has a Practice this in the sandbox button. Write your script, run it against realistic practice data and get it checked, with an interviewer's review of how it is written. No PDI needed. Nothing you run touches a real instance, and the data resets on every run.

Rehearse the real round: the Job Switch Kit has timed mock scripting rounds with random scenarios, no hints, PDI or notepad mode, and a score for every script.

Just want to code? Open the ServiceNow Script Editor: pick any question, let it ask you one at random, or try your own scripts in a free sandbox.

📘 Supported APIs and methods Tap to see what you can use in the practice editor

Scripts run as server-side background scripts, written in plain JavaScript the way ServiceNow expects (var, functions, arrays, JSON, Math). Press Ctrl+Space in the editor for suggestions.

GlideRecord also GlideRecordSecure

Query: addQuery, addEncodedQuery, addActiveQuery, addInactiveQuery, addNullQuery, addNotNullQuery, orderBy, orderByDesc, setLimit, getEncodedQuery, query, next, hasNext, get, getRowCount

Read: getValue, getDisplayValue, getUniqueValue, getTableName, getRecordClassName, isValid, isValidRecord, isNewRecord, isValidField, getLimit, getLastErrorMessage

Write: initialize, newRecord, setValue, setDisplayValue, insert, update, updateMultiple, deleteRecord, deleteMultiple, setWorkflow, autoSysFields, setForceUpdate, setUseEngines, setNewGuidValue

Security: canRead, canWrite, canCreate, canDelete

Or conditions: var qc = gr.addQuery(...); qc.addOrCondition(...)

GlideAggregate

addAggregate, getAggregate, groupBy, setGroup, orderByAggregate, addHaving, plus the GlideRecord query methods

Aggregates: COUNT, SUM, MIN, MAX, AVG

Fields gr.field, dot-walking

getValue, getDisplayValue, nil, getName, getLabel, getTableName, getReferenceTable, getRefRecord, setValue, changes, changesTo, changesFrom. Dot-walk references: gr.caller_id.email

gs

Logging: info, warn, error, debug, print, log, addInfoMessage, addErrorMessage

User and system: getUserID, getUserName, getUserDisplayName, hasRole, getProperty, setProperty, getMessage, nil, eventQueue

Dates: now, nowDateTime, nowNoTZ, daysAgo, daysAgoStart, daysAgoEnd, hoursAgo, minutesAgo, monthsAgo, beginningOfToday, endOfToday, beginningOfYesterday, beginningOfThisMonth, beginningOfLast7Days, beginningOfLast30Days, beginningOfThisYear, dateDiff and more

GlideDateTime and GlideDuration

GlideDateTime: getValue, getDisplayValue, setValue, getNumericValue, isValid, addSeconds, add, addDaysUTC / addDaysLocalTime, addWeeksUTC, addMonthsUTC, addYearsUTC, compareTo, before, after, onOrBefore, onOrAfter, equals, getDate, getLocalDate, getYearUTC, getMonthUTC, getDayOfMonthUTC, getDayOfWeekUTC

GlideDuration: getValue, getDisplayValue, getNumericValue, getDayPart, getRoundedDayPart

Query operators

= != < <= > >= IN, NOT IN, LIKE, NOTLIKE, STARTSWITH, ENDSWITH, ISEMPTY, ISNOTEMPTY, ANYTHING, ON, NOTON, and javascript:gs.daysAgoStart(7) style date values in encoded queries

Not available in the practice editor: chooseWindow, addJoinQuery, applyEncodedQuery, getLink, setAbortAction, getElements, gs.getSession, setting a field with field.setDisplayValue() (use gr.setDisplayValue('field', value) instead), Script Includes, GlideAjax and client-side APIs (g_form, g_user).

Write a script to show incident count for each state which are updated today?

We can use GlideAggregate API to achieve this scenario:

Script :

gs.print('State\\tIncident Count');
var grIncident=new GlideAggregate('incident');
grIncident.addEncodedQuery(' sys_updated_onONToday@javascript: gs.beginningOfToday()@javascript: gs.endOfToday()');
grIncident.addAggregate('COUNT','state');
grIncident.query();
while(grIncident.next()){
gs.print(grIncident.state. getDisplayValue()+'\t'+grIncident. getAggregate('COUNT','state'));
}

Output :


Note: This scripting question is common. However, they might ask for different table or different field. The primary learning here is whenever there is question related to finding count of the records, we are supposed to use GlideAggregate API. Do not use GlideRecord API with getRowCount method, it is not considered as best practice. Also make sure you understand how addAggregate, getAggregate and groupBy works in GlideAggregate API.

Write a script to print last 5 incidents created yesterday?

Script :


Output :


Note: Many of you must already be knowing how GlideRecord works but here interviewer checks if you know how setLimit, orderBy or orderByDesc can be used for such scenarios.

Write a script to print number of incidents Category and Sub Category wise?

We need to use GlideAggregate as we need to get count of incidents. Since, we need incidents Category and sub cateory wise, we need to apply grouping on 2 fields as shown below :

Script :


Output :


Note: Take away from this scenario is to understand how grouping on multiple fields can be used. Interviewer might change question to include 3-4 grouping fields so you should understand how grouping on multiple fields can be done via GlideAggregate API. Such multiple grouping logic is also quite useful if you want to do analysis on existing data.

Write a script as per below requirement :

1. You have to create one script inlcude with two function getIncidentDetails and sendDataToBackgroundScript.

2. getIncidentDetails should fetch first incident resolved today, this function should send Incident number, assignee user, resolved date and created date to sendDatToBackgroundScript function which is in the same script include.

3. sendDataToBackgroundScript function should calculate duration between created date and resolved date and return difference and Incident Number, Assignee User.

4. sendDataToBackgroundScript shoudl be called from background script and all data should be printed.

Background Script :


Script Include :


Output :


Note: Here interviewer tries to test your basic scripting knowledge, like calling script include from another script, sending multiple values from one function to another, finding date difference, basic usage of GlideRecord with setLimit and orderBy method. Interviewer might change scenarios to introduce more ServiceNow API's so prepare yourself with these all basic scripting knowledge.

Allow user to generate "Security Incident" via normal Incident record but we have to make sure that logged in user has access to "Security Incident" Table?

There are two methods to verify users access for any glide record.

1. Use GlideRecordSecure API while creating security incident. This API implicitly verifies if user passes ACL access on table.
2. Use canRead or canWrite function. These functions implicitly verifies if logged in user satisfies ACL access.

Write a script to print the number of open (active) incidents for every active assignment group, including groups that have no open incidents.

Counting means GlideAggregate, but there is a catch: GlideAggregate only returns groups that actually have incidents. To also show groups with 0, query the active groups separately and look up each count, defaulting to 0. That keeps it to two queries however many groups exist.

Script :

// 1. Count active incidents per group in ONE aggregate query
var counts = {};
var incAgg = new GlideAggregate('incident');
incAgg.addActiveQuery();
incAgg.addNotNullQuery('assignment_group');
incAgg.addAggregate('COUNT');
incAgg.groupBy('assignment_group');
incAgg.query();
while (incAgg.next()) {
    counts[incAgg.getValue('assignment_group')] = parseInt(incAgg.getAggregate('COUNT'), 10);
}

// 2. Walk every active group and print its count (0 when missing)
var groupGr = new GlideRecord('sys_user_group');
groupGr.addActiveQuery();
groupGr.orderBy('name');
groupGr.query();
while (groupGr.next()) {
    gs.info(groupGr.getValue('name') + ': ' + (counts[groupGr.getUniqueValue()] || 0));
}

Note: Interviewers use the "include zero" twist to see whether you understand what GlideAggregate returns. Looping over groups and calling getRowCount() for each one gives the same output but runs one query per group, which is the answer they are hoping you will not give.

Some employees have left the company, but open incidents are still assigned to them. Write a script to clear Assigned to on those incidents so the team picks them up, and print how many were unassigned.

Dot-walk to the assignee's user record inside the incident query: assigned_to.active=false. One query finds every affected incident; there is no need to loop over users first.

Script :

var count = 0;
var incidentGr = new GlideRecord('incident');
incidentGr.addEncodedQuery('active=true^assigned_to.active=false');
incidentGr.query();
while (incidentGr.next()) {
    incidentGr.setValue('assigned_to', '');
    incidentGr.update();
    count++;
}
gs.info('Unassigned ' + count + ' incident(s)');

Note: This is a common real-world clean-up. Keep the assignment group so the ticket goes back to the team's queue, and say why you let Business Rules run (no setWorkflow(false)) - the reassignment is a genuine change people should see.

Write a script to create a P1 incident for the caller "Anita Desai", assigned to the "Database" group, with short description "Production database is down", and print the new incident number.

Reference fields store sys_ids, but you don't need a separate query to find them: setDisplayValue() sets a reference by its display value (the name) on the incident itself. Check that both were found, then set the other values and insert(). On a real instance, priority is calculated from impact and urgency, so set those two.

Script :

var incidentGr = new GlideRecord('incident');
incidentGr.initialize();
// setDisplayValue() finds the reference by its display value (the name) and stores its sys_id
incidentGr.setDisplayValue('caller_id', 'Anita Desai');
incidentGr.setDisplayValue('assignment_group', 'Database');
if (incidentGr.caller_id.nil() || incidentGr.assignment_group.nil()) {
    gs.error('Caller or group not found');
} else {
    incidentGr.setValue('short_description', 'Production database is down');
    incidentGr.setValue('category', 'database');
    incidentGr.setValue('impact', 1);
    incidentGr.setValue('urgency', 1);
    incidentGr.insert();
    gs.info('Created ' + incidentGr.getValue('number'));
}

Note: setValue('caller_id', 'Anita Desai') is a classic mistake: setValue() expects the sys_id, so it stores a broken reference. setDisplayValue() is the one that takes the name. Dot-walking (caller_id.name) only reads through a reference and can't set one. Display values aren't unique either, so when two users can share a name, look the user up by user ID instead. And never hard-code sys_ids: they are different on every instance.

Write a script to print all active incidents that are Priority 1 or 2 and assigned to either the Network or the Database group, using a single encoded query.

^OR binds to the condition right before it, so (P1 OR P2) AND (Network OR Database) is written as below. An IN list is a shorter alternative: active=true^priorityIN1,2^assignment_group.nameINNetwork,Database.

Script :

var incidentGr = new GlideRecord('incident');
incidentGr.addEncodedQuery('active=true^priority=1^ORpriority=2^assignment_group.name=Network^ORassignment_group.name=Database');
incidentGr.query();
while (incidentGr.next()) {
    gs.info(incidentGr.getValue('number') + ' | ' + incidentGr.priority.getDisplayValue() + ' | ' + incidentGr.assignment_group.getDisplayValue());
}

Note: The trap is ^NQ: it does not mean "or" between two conditions, it starts a completely separate query. With ^NQ in the middle, every Database incident matches regardless of priority. Build the filter in a list view and use Copy query if you are unsure.

An audit found deactivated groups that still have members. Write a script to print every user who is a member of an inactive group.

Query the membership table sys_user_grmember and dot-walk to the group's active flag. One query answers the question.

Script :

var memberGr = new GlideRecord('sys_user_grmember');
memberGr.addQuery('group.active', false);
memberGr.query();
while (memberGr.next()) {
    gs.info(memberGr.user.getDisplayValue() + ' -> ' + memberGr.group.getDisplayValue());
}

Note: Knowing that sys_user_grmember is the many-to-many table between users and groups is the real test here. In an actual clean-up you would also remove these memberships, because users keep the roles inherited from the group.

Notifications are failing for some employees. Write a background script that prints the name and user ID of every active user who has no email address, sorted by name:

Script :

var userGr = new GlideRecord('sys_user');
userGr.addActiveQuery();
userGr.addNullQuery('email');
userGr.orderBy('name');
userGr.query();
while (userGr.next()) {
    gs.info(userGr.getValue('name') + ' (' + userGr.getValue('user_name') + ')');
}
  • addNullQuery('email') filters empty values in the database, so only the matching users are loaded.
  • Checking email == '' inside the loop gives the same output but reads every user in the table first. On a real instance with thousands of users, that difference matters.
  • addActiveQuery() is shorthand for addQuery('active', true).
Print how many active incidents are Priority 1 - Critical, as a single number:

Script :

var agg = new GlideAggregate('incident');
agg.addActiveQuery();
agg.addQuery('priority', 1);
agg.addAggregate('COUNT');
agg.query();
var count = 0;
if (agg.next()) {
    count = parseInt(agg.getAggregate('COUNT'), 10);
}
gs.info('Active P1 incidents: ' + count);
  • GlideAggregate asks the database for the count, so no records are loaded at all.
  • getRowCount() on a GlideRecord loads every matching record just to count them, and a counting loop does the same with extra work.
  • getAggregate() returns a string, so convert it with parseInt() before doing maths with it.
HR wants a headcount report. Print the number of active users in each department, using the department name. Users with no department appear as (no department):

Script :

var agg = new GlideAggregate('sys_user');
agg.addActiveQuery();
agg.addAggregate('COUNT');
agg.groupBy('department');
agg.query();
while (agg.next()) {
    var dept = agg.getDisplayValue('department') || '(no department)';
    gs.info(dept + ': ' + agg.getAggregate('COUNT'));
}
  • Grouping on a reference field groups by its sys_id, so print getDisplayValue() to show the name.
  • Users with no department form their own group with an empty value. Handling it explicitly is the detail interviewers look for.
  • One aggregate query covers every department, however many there are.
Print how many incidents were opened in the last 7 days for each priority, highest priority first:

Script :

var agg = new GlideAggregate('incident');
agg.addQuery('opened_at', '>=', gs.daysAgoStart(7));
agg.addAggregate('COUNT');
agg.groupBy('priority');
agg.orderBy('priority');
agg.query();
while (agg.next()) {
    gs.info(agg.getDisplayValue('priority') + ': ' + agg.getAggregate('COUNT'));
}
  • gs.daysAgoStart(7) is midnight at the start of the day 7 days ago, which is what people mean by "the last 7 days".
  • gs.daysAgo(7) keeps the current time of day, so anything opened earlier that morning drops out of the report.
  • orderBy('priority') sorts on the stored value, so 1 - Critical comes first.
Every active incident in the Software group with no Assigned to should go to the Software group's manager. Update them, then print how many were reassigned:

Script :

var grp = new GlideRecord('sys_user_group');
if (grp.get('name', 'Software')) {
    var managerId = grp.getValue('manager');
    var inc = new GlideRecord('incident');
    inc.addActiveQuery();
    inc.addQuery('assignment_group', grp.getUniqueValue());
    inc.addNullQuery('assigned_to');
    inc.query();
    var count = 0;
    while (inc.next()) {
        inc.setValue('assigned_to', managerId);
        inc.update();
        count++;
    }
    gs.info('Reassigned ' + count + ' incidents');
}
  • Read the manager once, outside the loop, instead of looking it up for every incident.
  • addNullQuery('assigned_to') plus addActiveQuery() limits the update to exactly the records that need it. Closed Software incidents stay as they are.
  • Looking the manager up from the group keeps the script correct when the manager changes. A hard-coded sys_id silently goes stale.
Build a comma-separated list of the sys_ids of all active incidents in the Network group, and print it on one line:

Script :

var ids = [];
var inc = new GlideRecord('incident');
inc.addActiveQuery();
inc.addQuery('assignment_group.name', 'Network');
inc.query();
while (inc.next()) {
    ids.push(inc.getUniqueValue());
}
gs.info(ids.join(','));
  • inc.sys_id is a GlideElement, not a string. The same object is reused as next() moves, so pushing it fills the array with references to one object, and every entry ends up as the last record's sys_id.
  • getUniqueValue() (or getValue('sys_id')) returns a plain string copy, which is what you want to store.
  • The same trap applies to any field: always store getValue() results, never the field objects.
For incidents in the Resolved state, print the average reassignment count for each assignment group, rounded to one decimal place:

Script :

var agg = new GlideAggregate('incident');
agg.addQuery('state', 6);
agg.addAggregate('AVG', 'reassignment_count');
agg.groupBy('assignment_group');
agg.query();
while (agg.next()) {
    var avg = parseFloat(agg.getAggregate('AVG', 'reassignment_count'));
    gs.info(agg.getDisplayValue('assignment_group') + ': ' + avg.toFixed(1));
}
  • AVG works like COUNT, but needs the field name both when you add it and when you read it.
  • Aggregate results come back as strings, so convert with parseFloat() before rounding.
  • One aggregate query gives every group's average, with no loop over the incidents.
Write a script that prints each problem with the number of active incidents linked to it.

Script :

var agg = new GlideAggregate('incident');
agg.addActiveQuery();
agg.addNotNullQuery('problem_id');
agg.addAggregate('COUNT');
agg.groupBy('problem_id');
agg.query();
while (agg.next()) {
    gs.info(agg.problem_id.getDisplayValue() + ': ' + agg.getAggregate('COUNT'));
}
  • GlideAggregate with groupBy('problem_id') returns one row per problem, with the count calculated by the database.
  • addNotNullQuery('problem_id') leaves out the many incidents that are not linked to any problem.
  • getDisplayValue() on the grouped reference gives the problem number, not its sys_id.
  • A problem's own state does not matter here: a closed problem with an incident still open is exactly what this report should surface.
For every change that was closed as Unsuccessful, print the incidents it caused, one line per incident.

Script :

var inc = new GlideRecord('incident');
inc.addQuery('caused_by.close_code', 'unsuccessful');
inc.orderBy('caused_by');
inc.orderBy('number');
inc.query();
while (inc.next()) {
    gs.info(inc.caused_by.getDisplayValue() + ': ' + inc.getValue('number'));
}
  • Start from the table that holds the link. Every incident has a caused_by reference, so one incident query answers the question.
  • Dot-walking inside addQuery() filters on the change's close code without loading any change records.
  • Starting from change_request and querying incidents per change works, but runs one extra query for every failed change.
  • In a post-incident review this is the first report people ask for: which change broke what.
Write the script for a daily scheduled job that reminds article owners exactly 7 days before a published knowledge article expires.

Script :

var kb = new GlideRecord('kb_knowledge');
kb.addQuery('workflow_state', 'published');
kb.addQuery('valid_to', '>=', gs.daysAgoStart(-7));
kb.addQuery('valid_to', '<=', gs.daysAgoEnd(-7));
kb.query();
while (kb.next()) {
    // parm1 = who gets the email, parm2 = the expiry date for the message
    gs.eventQueue('kb.article.expiring', kb, kb.getValue('author'), kb.getValue('valid_to'));
    gs.info(kb.getValue('number') + ' -> ' + kb.getDisplayValue('author'));
}
  • "Exactly 7 days" means the whole day 7 days from now: gs.daysAgoStart(-7) to gs.daysAgoEnd(-7). Comparing with a single timestamp would miss articles that expire at any other time that day.
  • Because the job runs every day, each article falls in that one-day window exactly once, so every owner gets one reminder, never two.
  • gs.eventQueue() only fires the event. A Notification on kb_knowledge, sent when kb.article.expiring fires, with Event parm 1 contains recipient ticked, sends the email. Register the event in the Event Registry first.
  • Firing an event instead of sending email from the script keeps the wording editable by admins and puts every reminder in the email log.
  • Only published articles need a reminder: drafts and articles in review are not visible to users anyway.

While you're deciding, someone else applying for the same role already started their 15-day plan.

No countdown, no gimmick, just a head start you can still catch up on.

500+ Q&A — Technical + Behavioral, structured by module
15-Day Structured Roadmap — Day-by-day plan that peaks on interview day
Unlimited Interview Bot — Practice live, every session recorded and reviewable
Scripting Editor + Mock Round: Run real scripts, then a timed scripting round with interviewer review
Salary Negotiation Playbook — Counter-offers, CTC decoding, in-hand strategy
Job Switch Strategy Guide — Notice period, BGV, resignation, offer comparison
Progress Tracker + Notes — Always know exactly what to tackle next
LinkedIn Profile Optimisation — Get found by recruiters before you even apply
Catch Up →

🔒 Secure payment via Razorpay · Instant access after payment

Real Interview Questions & Answers

Questions shared by ServiceNow professionals and reviewed for clarity, relevance, and interview usefulness.

Apurva 15 Oct 2025
Given an array, find the duplicates of in the array and return an object with duplicate number and its index input = [1,2,3,1] output = { 1 : [1,4]}
Keerthi Kiran M 13 Nov 2025
var arr= [1,2,3,1]; var duplicate = {}; for(var i=0; i< arr.length; i ){ if(duplicate[arr[i]]){ duplicate[arr[i]].push(i); }else{ duplicate[arr[i]]=[i]; } } var result = {}; for(var key in duplicate){ if(duplicate[key].length > 1){ result[key] = duplicate[key]; }} console.log(result); //output: { '1': [ 0, 3 ] }
0 helpful
0 helpful
*Please enter a reply
Apurva 15 Oct 2025
Using a ServiceNow code, find your age.
Sowmya 08 Feb 2026
(function () { var dob = '1996-09-20'; var dobGDT = new GlideDateTime(dob); var today = new GlideDateTime(); var age = GlideDateTime.subtract(today,dobGDT).getYears(); gs.info("your age is:" age); })();
0 helpful
0 helpful
*Please enter a reply
Apurva 15 Oct 2025
Create a table with 2 fields - Employee Name and Salary. Add 3-5 entries. Employee Name Salary Raj 2000 Keshav 3000 Seema 5000 Jason 6000 Using a ServiceNow code, Display the name of the employee with second highest salary
Durga Prasad 24 Mar 2026
var employeeList = [ { name: 'Raj', salary: 2000 }, { name: 'Keshav', salary: 3000 }, { name: 'Seema', salary: 5000 }, { name: 'Jason', salary: 6000 } ]; // Sort descending by salary employeeList.sort(function(empA, empB) { return empB.salary - empA.salary; }); // Get second highest var secondHighestEmployee = employeeList[1]; gs.print('Second highest salary employee: ' secondHighestEmployee.name);
0 helpful
0 helpful
*Please enter a reply
Ani 23 Aug 2025
I want to create change task a b c d e and short description a1 b1 c1 d1 e1 When ever change moves to implement state How cam we achieve this scenario
0 helpful
*Please enter a reply
Akshay 10 Jul 2025
If Assigned To user is not active, then assign the incident to the Assigned To's manager" in ServiceNow ITSM
Surya 06 Apr 2026
what is manager is not part of the assignment group
0 helpful
0 helpful
*Please enter a reply
Jasprit 24 Dec 2024
What is the difference between the newRecord and initialize method of GlideRecord?
Swappy 07 Feb 2025
What is servicenow gliderecord initialize ? Creates an empty record within the current GlideRecord that is suitable for population before an insert. What is servicenow gliderecord newRecord? Creates a GlideRecord, sets the default values for the fields, and assigns a unique ID to the record.
0 helpful
0 helpful
*Please enter a reply
Zorro 29 Sep 2024
Suppose there are multiple duplicates for multiple records in a incident table now I want to know all the records which have duplicates, how can I be able to achieve it?
Manoj D 02 Nov 2024
var incidentGr = new GlideAggregate('incident'); incidentGr.addAggregate('COUNT', 'number'); incidentGr.groupBy('number'); incidentGr.query(); while (incidentGr.next()) { var count = incidentGr.getAggregate('COUNT', 'number'); if (count > 1) { gs.info('Duplicate Record: ' incidentGr.number ' Count: ' count); } }
0 helpful
Srinidhi 28 Aug 2025
gs.print(getDuplicates('incident','number')); // Assuming you have duplicate Incident Numbers function getDuplicates(tablename,val) { var dupRecords = []; var gaDupCheck = new GlideAggregate(tablename); gaDupCheck.addQuery('active','true'); gaDupCheck.addAggregate('COUNT',val); gaDupCheck.addNotNullQuery(val); gaDupCheck.groupBy(val); gaDupCheck.addHaving('COUNT', '>', 1); gaDupCheck.query(); while (gaDupCheck.next()) { dupRecords.push(gaDupCheck[val].toString()); } return dupRecords; }
0 helpful
0 helpful
*Please enter a reply
Pragya 15 Jun 2024
Print user's manager's manager name and email address using client script and script include.
0 helpful
*Please enter a reply
Chandu 22 May 2024
How to pass values between two functions in Script Include
Abhinandan 09 Jun 2024
You can use function arguments to send in data from one function to other.
2 helpful
Sharique 07 Sep 2026
I guess you mean, in a script include there are two functions and you want to access variables defined in one function into another. You can make use of the 'this' leywpord for accessing the value.
0 helpful
0 helpful
*Please enter a reply
Ghouse Sharief 30 Mar 2024
Populate an alert or info message on incident form when assignment group changes on the incident . on the alert display the assignment group members
Sumit 04 Oct 2024
we have to use onchange client script for displaying alert , and for fetching assignment group members we hvae to write script include which will return the list of all members in that group
0 helpful
N Cinthala 07 Aug 2025
script include: var namearr=[]; var y=this.getParameter('sysparm_value'); var x=new GlideRecord('sys_user_grmember'); x.addQuery('group',y); x.query(); while(x._next()){ namearr.push(x.user.name ''); } return namearr ''; client script: var z=new GlideAjax('test123'); z.addParam('sysparm_name','demo'); z.addParam('sysparm_value',newValue); z.getXMLAnswer(hello); function hello(response){ alert(response ''); }
1 helpful
0 helpful
*Please enter a reply
Sk 30 Mar 2024
Hi, I was asked this scenario : If Assignment group and state is changed to particular choice Short description should become Mandatory and Description should become read only
Dhruv 27 Apr 2024
You can use UI Policy UI Policy condition - Assignment Group is [Service Desk] AND state is [New] UI Policy Action: Make short description field Mandatory Description filed Read Only
1 helpful
0 helpful
*Please enter a reply
Chandu 19 Mar 2024
Difference between addQuery and addEncodedQuery methods
Nikhil Kamlekar 01 Apr 2024
addQuery or addEncodedQuery methods we usually use in querying the records. Ex: If you have one query needs to be run, you can use addQuery('category','software); If you have multiple queries then for each time you have to use addQuery instead of multiple queries you can use addEncodedQuery addEncodedQuery('paste the query here')
0 helpful
0 helpful
*Please enter a reply
Sneha 08 Mar 2024
If I create ITIL user it will automatically added in manager group how can I do this?
Ajay 08 Oct 2024
There is a table called "sys_user_has_role" , write a Before BR on this table on insert, with the condition as role is ITIL and in the code you can include as below var user_sys_id=current.user; // this will fetch the user with that got assigned the itil role var gr=new gliderecord('sys_user_gr_member'); gr.initialize(); gr.group="Manager group sysid"; gr.user=user_sysid; gr.insert();
0 helpful
0 helpful
*Please enter a reply
Cookie 06 Mar 2024
If an incident is in resolved state for 5 days, Close it
Anjali Singh 25 Mar 2024
1. Navigate to System Properties > System. 2. Locate the property Number of days (integer) after which Resolved incidents are automatically closed. 3. Set the Value to be the number of days to wait before closing a resolved incident.
0 helpful
Sharique 07 Sep 2026
Anjali answer is right. You can also create a scheduled job which will run daily and updates the records. Below is the code for the same var gr = new GlideRecord("incident"); gr.addQuery('state','6'); gr.addQuery('sys_updated_on','>',gs.daysAgo(5)); gr.query(); var total = gr.getRowCount(); gs.log('total row : ' +total); while(gr.next()){ gr.state = 7; gs.log("Incident has closed"); gr.update(); }
0 helpful
0 helpful
*Please enter a reply
Cookie 06 Mar 2024
Print system date and date a year ago
Pradeep 15 Apr 2024
var gdt = new GlideDateTime(); gdt.addYears(-1); gs.print(gdt.getDate());
0 helpful
0 helpful
*Please enter a reply
Cookie 06 Mar 2024
Insert 10 incidents from Incident table in an array
Heisenberg 24 Dec 2024
var incident_list=[]; var incidentGr=new GlideRecord('incident'); incidentGr.addEncodedQuery('active=true'); //Replace query based on the input incidenGr.setLimit(10); incidentGr.query(); while(incidentGr.nect()){ var obj={}; //Empty object //Push attributes according to your choice. For now I am pushing only number and short description obj.number=incidentGr.getValue('number'); obj.short_description=incidentGr.getValue('short_description'); incident_list.push(obj); } //Print List for(var i=0;i<incident_list.length;i ){ gs.info('Number: ' incident_list[i].number ' Short Description ' incident_list[i].short_desciption '\n'); }
0 helpful
Divesh Jalandriya 22 May 2025
var arrayList = []; var grIncident = new GlideRecord('incident'); grIncident.setLimit(10); grIncident.query(); while (grIncident.next()) { var obj = {}; obj.number = grIncident.number.getDisplayValue(); obj.short_description = grIncident.short_description; arrayList.push(obj.number '->' obj.short_description); } for(var i=0;i<arrayList.length;i ) { gs.info(arrayList[i]); } gs.info(arrayList.join(','));
0 helpful
0 helpful
*Please enter a reply
Cookie 06 Mar 2024
Read Caller's name from the Caller field in incident table, and check for 1st letter, if it is a, print "apple", if it is b, print "bat"
Pradeep 21 Apr 2024
var caller = current.caller_id.getDisplayValue(); var text = caller.toUpperCase(); if (text.startsWith('A')) gs.print('Apple'); else gs.print('Bat');
0 helpful
0 helpful
*Please enter a reply
Naveen 01 Mar 2024
2.When the Caller field is changed, retrieve the caller's location and update the Location field accordingly.
Ajay 08 Oct 2024
you can achieve this with a on change client script and script include
0 helpful
0 helpful
*Please enter a reply
Sujatha 28 Feb 2024
when ever the problem work note updated,update the comment in attached incident work notes also
Nithin 03 Jul 2025
script in problem table >> var inc = new GlideRecord('incident'); inc.addQuery('problem_id', current.sys_id); inc.query(); while (inc.next()) { inc.work_notes = current.work_notes; inc.update(); }
0 helpful
0 helpful
*Please enter a reply
Ann 25 Oct 2023
when I submit a new request on behalf of "xyz" when xyz opens that form should be editable for "xyz" and other forms should be read only to xyz how can I achieve this.
Abdul 16 Nov 2023
created_by field will store your name and requested_by field will store 'XYZ'. NOw you can USE ACL or combination of Display BR and Client script
1 helpful
Pratiksha 24 Nov 2023
suppose you create incident on behalf of xyz the you can achieve above requirement in two ways. 1.create write ACL (in script check if logged in user is caller) 2. create display BR and onLoad client script
0 helpful
Isha 28 Nov 2023
ACL
0 helpful
Astik Thombare 04 Dec 2023
Hi @Ann, You can create a new ACL on the incident table with the operation "write" and name it "Incident." Set the conditions to "None" and give the condition that the caller is dynamic. This way, you can achieve the above requirement. Thanks! Astik
2 helpful
Satyam Jain 02 Mar 2024
Create write ACL on the table.none and write the script in advance answer=false; var gr=gs.getUserID(); if(current.caller_id==gr){ answer=true; }
0 helpful
0 helpful
*Please enter a reply
Ann 25 Oct 2023
when user clicks on new form incident form will open, when user opens a new option that time in the state "cancel" option should be hidden. Once he submits a form "cancel" option should be visible. how to achieve this
Snowexpertaastik 05 Sep 2025
if(g_form.isNewRecord()){ g_form.removeOption('state','8'); }
0 helpful
0 helpful
*Please enter a reply
Ann 25 Oct 2023
on the catalog form below the submit button i want to add reset button which will reset all the values. How to achieve this
0 helpful
*Please enter a reply
Harish Gadi 07 Sep 2023
How to create a problem record for 5 th incident in incident list Example: there are 10 incidents we need to create a problem ticket for incident for 5 th incident only ?
Surendra 24 Oct 2023
var gr = new GlideRecord('incident'); gr.orderByDesc('sys_created_on'); //gr.setLimit(10); gr.chooseWindow(4,5);// 4-first row and 5- last row gr.query(); while(gr.next()){ gs.print(gr.number); // create problem record here }
0 helpful
0 helpful
*Please enter a reply
Satyapriya Biswal 05 Aug 2023
I was asked that write a background script that will show how many roles the current logged in user have. Can anyone help me to answer this question.
Aastha 06 Aug 2023
var gr = new GlideRecord('sys_user_has_role'); gr.addQuery('user','6816f79cc0a8016401c5a33be04be441') gr.query(); gs.print(gr.getRowCount()); while(gr.next()) { //one way to do it }
0 helpful
Ps 07 Aug 2023
var userid = gs.getUserID(); var gr = new GlideRecord('sys_user_has_role'); gr.addQuery('user.sys_id', userid); gr.query(); while(gr.next()){ gs.print(gr.role.getDisplayValue()); gs.print(gr.getRowCount()); }
0 helpful
Ria 23 Aug 2023
Whenever we have to find out count of something then it is recommended to use GlideAggregate API, using GlideRecord API with getRowCount method is not efficient and it is not considered as best practice. Therefore you can rather use below code. var userid = gs.getUserID(); var gaRoleCount=new GlideAggregate("sys_user_has_role"); gaRoleCount.addQuery("user",userid); gaRoleCount.addAggregate("COUNT","role"); gaRoleCount.query(); if(gaRoleCount.next()){ gs.print("Role Count for logged in user:" gaRoleCount.getAggregate("COUNT","role"); }
1 helpful
Satyapriya Biswal 25 Aug 2023
Thanks
0 helpful
Praveen K 20 Sep 2023
Hi Ria, In 4th line you are grouping the count by role which is incorrect it should be only gaRoleCount.addAggregate("COUNT"); Check below code for more info var userid = gs.getUserID(); var gaRoleCount=new GlideAggregate("sys_user_has_role"); gaRoleCount.addQuery("user",userid); gaRoleCount.addAggregate("COUNT"); gaRoleCount.query(); if(gaRoleCount.next()){ //gs.print(gs.getUserName()) //gs.print(userid) gs.print("Role Count for logged in user:" gaRoleCount.getAggregate("COUNT")); }
1 helpful
Bharath 12 Jul 2024
gs.print("Role Count for logged in user:" gaRoleCount.getAggregate("COUNT")) in this line was error in background script, Please once check it Tank You..
0 helpful
Anonymous 23 Feb 2026
var a=gs.getUser().getRoles(); gs.log(a); gs.log(a.size());
0 helpful
0 helpful
*Please enter a reply
Swetha 16 Jul 2023
During my interview, I was asked to write a script where I need to return a user's Manager's Manager(Seniormanager). If the field is empty, in that case i have to return his above level manager (Director). Can you help me with the solution code.
Praveen K 20 Sep 2023
Try using Dot walking and if statement for example - var gr = new GlideRecord('sys_user') gr.addQuery('sys_id','02826bf03710200044e0bfc8bcbe5d88'); gr.query(); if (gr.next()){ gs.print('User Name - ' gr.name) gs.print('Manager Name - ' gr.manager.name) if(gr.manager.manager.name){ gs.print('Managers Manager Name - ' gr.manager.manager.name) //Make sure that managers field is populated in users and managers record } else{ gs.print('Director Details (I dont have director so not displaying)') } }
0 helpful
0 helpful
*Please enter a reply
Mohit Singhal 01 Apr 2023
Write Background script code to Make all the incidents active as false whose caller starts with 's'.
Kushal 03 Apr 2023
There is small trick in this scenario. Many developer don't know that we can dot walk caller name in encoded query itself (2nd line in below script). Instead developers glide into all incidents and then they add if condition to check if caller name startswith s, which is valid solution but not efficient one. Script :var grIncident=new GlideRecord("incident"); grIncident.addEncodedQuery("caller_id.nameSTARTSWITHs"); //Here dot walk is very important, very useful in many scenarios grIncident.query(); while(grIncident.next()){ grIncident.setValue("active",false); grIncident.update(); }
1 helpful
Prerna 03 Apr 2023
Thanks Kushal. I never knew dot walk work this way as well.
1 helpful
Rakesh 06 Apr 2023
Hey Kushal, Your script works but it is not efficient. In this case we can rather use updateMultiple method as we are going to update same value for all filtered records ( that is making it false ). Interviewer normally expects efficient script from candidates. We can use below script : var grIncident=new GlideRecord("incident"); grIncident.addEncodedQuery("caller_id.nameSTARTSWITHs"); grIncident.query(); grIncident.setValue("active",false); grIncident.updateMultiple();
1 helpful
Mohit Singhal 01 May 2023
As I have read , Incident's Active is set to false when Incident state is Closed or Cancelled.
1 helpful
Astik 04 Dec 2023
var gr = new GlideRecord('incident'); gr.addEncodedQuery('caller_idSTARTSWITHs^ORcaller_idSTARTSWITHWITHS'); gr.query(); while(gr.next()){ gr.setValue('active',false); gr.update(); }
0 helpful
Ashutosh Kumar 20 Oct 2024
you need to change state of new cases to canceled/closed/resolve than only you can set Active false. var gr = new GlideRecord('incident'); gr.addEncodedQuery('caller_idSTARTSWITHs^active=true'); gr.query(); while(gr.next()){ gr.state=8; gr.active=false; gr.update(); }
0 helpful
0 helpful
*Please enter a reply
Share a Question
?
Questions are reviewed before publishing to maintain quality. Include the role, scenario, or context if possible — specific questions are more useful to others.

🚀 Power Up Your ServiceNow Career

Join a growing community of smart ServiceNow professionals to stay ahead in interviews, sharpen your development skills, and accelerate your career.

📱

ServiceNow Buddy App

Get the free Android app for a smoother experience.

Install
Comments 2
S
Sonali 31 Jan 2025
This is a brilliant set of questions and answers! I�ve been asked many of these questions repeatedly. I must also admit, I�m finding the user-shared questions incredibly interesting and valuable for my interview preparation. I am just loving the fact that everyone is contributing their questions and answers here.
P
Prerna 03 Apr 2023
I can't express how much your content is useful for me. Around 70% questions were asked to me are from your set of question and answers. Now I am able to crack L1 interviews easily.
* Please enter a comment before submitting.
📝 My Topic Notes 🔒 Only visible to you
Previous Scenario Based Questions Next ACL Questions

Found these questions helpful?

Share your experience — it helps other ServiceNow professionals know what to prepare.

Share Your Story →