When writing scripts for the "Background Scripts" module in ServiceNow, it's important to keep in mind that the platform allows you to interact with the ServiceNow database and provides a way to manipulate and retrieve data via GlideRecord and GlideAggregate. Below are some simple scripting exercises that you can implement as background scripts to print output:
1. Print All Records from a Table
This simple script will fetch and print all records from the cmdb_ci table.
var gr = new GlideRecord('cmdb_ci');
gr.query();
while (gr.next()) {
gs.print("CI Name: " + gr.getValue('name') + " - Sys ID: " + gr.getValue('sys_id'));
}
2. Count the Number of Records in a Table
This script will count and print the number of records in the incident table.
var gr = new GlideRecord('incident');
gr.query();
var count = gr.getRowCount();
gs.print("Total number of incidents: " + count);
3. Find and Print Duplicate Values
This script finds and prints duplicate name values in the cmdb_ci table.
var ga = new GlideAggregate('cmdb_ci');
ga.addAggregate('COUNT', 'name');
ga.groupBy('name');
ga.addHaving('COUNT', '>', 1);
ga.query();
gs.print("Duplicate CI Names:");
while (ga.next()) {
gs.print("Name: " + ga.getValue('name') + " - Count: " + ga.getAggregate('COUNT', 'name'));
}
4. Update Records Based on a Condition
This script updates all active incidents to set their priority to 1.
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.query();
while (gr.next()) {
gr.priority = 1; // Set priority to 1
gr.update();
gs.print("Updated incident: " + gr.getValue('number'));
}
5. Print Class Relationships in CMDB
This script fetches all CIs and prints their class and sys_id.
var gr = new GlideRecord('cmdb_ci');
gr.query();
gs.print("CI Classes and Sys IDs:");
while (gr.next()) {
gs.print("Class: " + gr.getValue('sys_class_name') + " - Sys ID: " + gr.getValue('sys_id'));
}
6. List Users and Their Roles
This script lists all users and their roles from the sys_user and sys_user_has_role tables.
var userGr = new GlideRecord('sys_user');
userGr.query();
while (userGr.next()) {
var userRoles = [];
var roleGr = new GlideRecord('sys_user_has_role');
roleGr.addQuery('user', userGr.sys_id);
roleGr.query();
while (roleGr.next()) {
userRoles.push(roleGr.role.getDisplayValue());
}
gs.print("User: " + userGr.getValue('name') + " - Roles: " + userRoles.join(', '));
}
Best Practices
- Always test your scripts in a sub-production environment before running them in production.
- Consider adding exception handling to your scripts to manage potential errors.
- Use
gs.info(), gs.warn(), and gs.error() for different output levels instead of just gs.print().
- Make sure that your script adheres to the platform best practices, especially concerning performance.
You can paste any of these scripts directly into the "Background Scripts" module in ServiceNow and execute them to see the output in the system logs.