Skip to content
Background Script Repository

Background Script Repository

A curated collection of snippets for quick platform administration.

Note: Always run scripts in a sub-production instance first. Use gs.info() to verify data before executing updates.

Approval Audit Report (RITM)

Quickly see a summary of all Catalog Item approvals for a specific user, including counts by item type and record reference.

The Problem

When auditing a user’s activity or preparing for offboarding, it’s difficult to see a high-level summary of what types of requests they are approving without looking at dozens of individual records.

The Solution

This script filters the sysapproval_approver table for a specific user and class (RITM), then aggregates the results by Catalog Item name to provide a clear summary.

Group Approval Audit Report

Summarize approvals for a specific group, showing counts by Catalog Item and listing each approval record and by member breakdown.

The Problem

When auditing group owned approvals, it is difficult to see which Catalog Items the group is responsible for without manually reviewing each record. Additionally, tracking individual accountability within the group specifically, identifying which members are actively approving or rejecting requests is highly manual.

The Solution

This script queries the sysapproval_group table for a specific Assignment Group filtering on Requested Items (sc_req_item). It aggregates the data by Catalog Item type and outputs a detailed breakdown listing the Group Approval Sys ID, the RITM Sys ID, and the specific group Approval State (e.g., Requested, Approved, Rejected).

Validate Schedule

Ensures a requested date has sufficient lead time based on a specific schedule (e.g. business hours, exluding weekends and holidays) and a defined minimum duration (e.g. 3 business days).

The Problem

When enforcing lead times for processes like Change Management or Catalog Requests, it is difficult to accurately calculate if a user has provided enough notice. A simple date subtraction doesn’t account for weekends, holidays, or after-hours.

The Solution

This script uses ServiceNow’s GlideSchedule API to calculate the exact amount of working time between a start date and an end date based on a specific schedule (e.g., 8 AM - 5 PM). It then checks if that working duration is at least 3 business days (which equals 27 business hours in an 8-5 schedule) and returns a success or failure message.

Bulk Attachment Deletion (Dry-Run)

Permanently deletes every attachment on a specific record, with a dry-run flag to preview what would be destroyed before actually running the deletion.

This script permanently deletes attachments when dryRun is set to false — deleteAttachment() wipes both the sys_attachment metadata record and the underlying binary data in sys_attachment_doc, with no soft-delete or recycle bin to recover from. Always run with dryRun = true first and confirm tableName/recordSysId point at the intended record before flipping it to false.

The Problem

Cleaning up attachments on a record (before deleting the record itself, removing sensitive or erroneous files, or as part of a data cleanup effort) is manual and easy to get wrong when done one attachment at a time through the UI, especially against the wrong record.

The Solution

This script queries sys_attachment for every attachment tied to a given table_name and table_sys_id, then uses the GlideSysAttachment API to destroy each one. A dryRun flag controls whether it only prints what it would delete, or actually performs the deletion.

Generic Table-Field Dumper

Quickly query any table/field combination and format the output as tab-delimited (paste into Excel/Sheets) or comma-delimited quoted values, with no CSV export needed.

The Problem

Pulling a quick list of field values off a table for a spreadsheet or a one-off IN query usually means exporting a list to CSV or copy-pasting from a list view, which is slower than just running a script when you already know the table, field, and filter you want.

The Solution

This script queries any tableName/fieldNames pair against an encodedQuery, then prints the results twice: once as tab-delimited rows (paste straight into a spreadsheet), and once as quoted, comma-separated values (handy for building an IN clause). useDisplayValues toggles between human-readable and raw backend values, and rowLimit optionally caps how many rows are returned.

Audit Assets Missing CI or Multiple Contracts

Two related HAM (Hardware Asset Management) data-integrity checks: one flags serial numbers that don’t have a matching record on both the Asset and CI tables, the other flags assets linked to more than one contract.

Please note the highlighted line(s) for where to change inputs

Asset-CI exists check.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
 * Script Name: Asset-CI Exists Check
 * Description: Validates that serial numbers exist in both the Hardware Asset table and Computer CI table.
 * 
 * Usage: Background script to audit asset and CI records for consistency.
 * 
 * Example Output:
 * *** Script: Starting validation for 18 serial numbers...
  *** Script: === VALIDATION SUMMARY ===
  *** Script: 
  ❌ MISSING BOTH (No Asset and No CI) [1]:
  *** Script: --------------------------------------------------
  *** Script: JGJFNSGJU3
 * 
 * Author: Konner Lester
 * Date Created: 6/1/2026
 */

(function() {
  // Paste a raw, line-separated list of serials inside the template literal
	var rawSerials = `
	MXL8htfg4h
	MXLghvbtyi
	MXL634dfg5
	`;

	// This splits the block line-by-line into a clean array automatically
	var serialsToCheck = rawSerials.split('\n');

  var missingAssets = [];
  var missingCIs = [];
  var missingBoth = [];
  
  gs.print("Starting validation for " + serialsToCheck.length + " serial numbers...\n");

  for (var i = 0; i < serialsToCheck.length; i++) {
      // Clean up the string to ensure a reliable query
      var serial = serialsToCheck[i].trim();
      if (!serial) continue;

      var hasAsset = false;
      var hasCI = false;

      // Check Hardware Asset Table
      var assetGR = new GlideRecord('alm_hardware');
      assetGR.addQuery('serial_number', serial);
      assetGR.setLimit(1); // Efficiency: stop looking after finding one
      assetGR.query();
      if (assetGR.next()) {
          hasAsset = true;
      }

      // Check Computer CI Table
      var ciGR = new GlideRecord('cmdb_ci_computer');
      ciGR.addQuery('serial_number', serial);
      ciGR.setLimit(1);
      ciGR.query();
      if (ciGR.next()) {
          hasCI = true;
      }

      // Categorize results
      if (!hasAsset && !hasCI) {
          missingBoth.push(serial);
      } else if (!hasAsset) {
          missingAssets.push(serial);
      } else if (!hasCI) {
          missingCIs.push(serial);
      }
  }

  // 2. Output the Results
  gs.print("=== VALIDATION SUMMARY ===");
  
  if (missingBoth.length === 0 && missingAssets.length === 0 && missingCIs.length === 0) {
      gs.print("SUCCESS: All serial numbers have matching Assets AND CIs!");
      return;
  }

  if (missingBoth.length > 0) {
      gs.print("\n❌ MISSING BOTH (No Asset and No CI) [" + missingBoth.length + "]:");
      gs.print("--------------------------------------------------");
      gs.print(missingBoth.join("\n"));
  }

  if (missingAssets.length > 0) {
      gs.print("\n⚠️ MISSING ASSET RECORD ONLY (CI Exists) [" + missingAssets.length + "]:");
      gs.print("--------------------------------------------------");
      gs.print(missingAssets.join("\n"));
  }

  if (missingCIs.length > 0) {
      gs.print("\n⚠️ MISSING CI RECORD ONLY (Asset Exists) [" + missingCIs.length + "]:");
      gs.print("--------------------------------------------------");
      gs.print(missingCIs.join("\n"));
  }

})();

Find Fields with Duplicate Values

Several ways to find duplicate values in a field, ranging from a no-script UI method to background scripts that look up display names or build a URL straight to the offending records.

Method 1 - Group By Column (No Script)

For a quick, one-off check with no script required:

  1. Navigate to the list view of the table.
  2. Right-click the column header you want to check and select Group By [column name].
  3. Any group with more than one record under it contains a duplicate value.

Method 2 - Basic Duplicate Check (GlideAggregate)

The simplest script-based approach. GlideAggregate groups records by a field, counts how many rows share each value, then filters with addHaving() to only keep groups with more than one record.

The Problem

Finding duplicate values by eye in a large list is slow, and Group By only shows counts in the UI without an easy way to act on the results in a script.

The Solution

This script queries any table/field pair and prints every value that occurs more than once, along with its count. Swap table and field for whatever you need to check.

Method 3 - Duplicate Check with Display Name (Reference Fields)

When the duplicated field is a reference (e.g. approver pointing to sys_user), the raw value returned is a sys_id. This variation looks up each duplicated sys_id against its source table to print a human-readable name instead.

The Problem

Running the basic duplicate check against a reference field returns a list of sys_ids, which isn’t useful without manually looking each one up.

The Solution

After finding duplicated values, this script looks up each one on the referenced table (e.g. sys_user) and prints a display field of your choice — such as name — instead of the sys_id.

Method 4 - Duplicate Serial Numbers with Generated URL

Once you know a field has duplicates, it’s useful to jump straight to those records instead of searching for each value manually. Both variations below build a list URL filtered to just the duplicate values found.

The Problem

Knowing that duplicates exist still leaves the manual work of pulling up each record to compare and resolve them.

The Solution

Two variations, depending on whether you already have a specific list of serial numbers to check, or want to scan the whole table:

  • Check a specific list — pass in known serial numbers and confirm which of them are actually duplicated.
  • Scan the whole table — same duplicate logic as Method 2, but collects the results into an array instead of just printing them.

Both build an IN encoded query from the duplicate values and print a ready-to-click list URL.

Last updated on