Skip to Content

ServiceNow Scripts Library

A comprehensive collection of ready-to-use ServiceNow scripts for common use cases. Search, filter, copy, and customize these battle-tested solutions.

View:

Client Scripts

Client Scripts run in the user's browser and control form behavior in real-time. Use them for UI manipulation, field validation, and user interaction.

Auto-populate Related Fields

Automatically populate fields when a reference field changes (e.g., populate caller's phone and email when caller is selected).

Type: onChange Table: incident Field: caller_id
reference-fieldauto-populateformonChange

Conditional Mandatory Fields

Make fields mandatory based on the value of another field (e.g., require close notes only when state is Resolved).

Type: onChange Table: incident Field: state
mandatory-fieldsconditionalvalidationonChange

Dynamic Field Visibility

Show or hide fields based on another field's value (e.g., show "Other reason" field only when user selects "Other" from dropdown).

Type: onChange Table: incident Field: category
visibilityshow-hideconditionalonChangeonLoad

Reference Field Filtering

Filter options in a reference field based on another field's value (e.g., show only assignment groups for the selected category).

Type: onChange Table: incident Field: category
reference-fieldfilterdependent-fieldsonChange

Prevent Form Submission

Validate form data and prevent submission if conditions aren't met (e.g., prevent closing ticket without resolution notes).

Type: onSubmit Table: incident
validationonSubmitform-submissionprevent-save

GlideAjax Server Call

Call server-side Script Include from client-side to fetch data or perform operations without page refresh.

Type: onChange Table: incident Field: caller_id
glideajaxajaxserver-callasynconChange

Real-time Field Validation

Validate field input in real-time and provide immediate feedback to users (e.g., check format, valid values, etc.).

Type: onChange Table: incident Field: u_email
validationreal-timeonChangefield-validationemailregex

Confirmation Dialog Before Save

Show a confirmation dialog before saving the form when certain conditions are met (e.g., warn user about critical changes).

Type: onSubmit Table: incident
confirmationonSubmitdialoguser-warningvalidation

Populate Fields from Current User

Automatically populate form fields with the current logged-in user's information (e.g., pre-fill requester details).

Type: onLoad Table: incident
onLoadcurrent-userauto-populateuser-infoglideajax

Calculate Field Values Dynamically

Automatically calculate field values based on other fields (e.g., calculate total cost, days between dates, percentage).

Type: onChange Table: incident Field: u_quantity
calculationonChangedynamicmathauto-calculatetotal

Role-based Section/Field Visibility

Show or hide sections or specific fields based on the current user's roles, useful for restricting sensitive information access.

Type: onLoad Table: incident
onLoadrolessecurityvisibilityrbacsections

Debounced Search with GlideAjax

Implement a debounced search to avoid excessive server calls when users type in a search field, improving performance.

Type: onChange Table: incident Field: u_search_field
onChangesearchdebounceperformanceglideajaxoptimization

Multi-field Dependent Validation

Validate combinations of multiple fields together, such as ensuring end date is after start date or validating business logic across fields.

Type: onSubmit Table: change_request
onSubmitvalidationmulti-fieldbusiness-logicdate-validationcomplex-validation

Auto-save Draft Functionality

Periodically save form data automatically to prevent data loss if browser crashes or session expires.

Type: onLoad Table: incident
onLoadauto-savedraftlocalStoragedata-loss-preventionuser-experience

Field Help Text Toggler

Show contextual help text or tooltips for specific fields to guide users, with ability to toggle help on/off.

Type: onLoad Table: incident
onLoadhelptooltipuser-guidancetraininguser-experience

Prevent Duplicate Submission

Disable the submit button after first click to prevent duplicate record creation from double-clicks or multiple submissions.

Type: onSubmit Table: incident
onSubmitvalidationduplicate-preventionsubmit-buttonuser-experienceform-control

Custom Date Range Validation

Validate date fields against each other with custom business rules like working days, blackout periods, and lead times.

Type: onChange Table: change_request Field: start_date
onChangedate-validationbusiness-rulesblackout-dateslead-timechange-management

ACL Debug Visualizer

Type: Client Script Table: sys_security_acl
ACLSecurityDebuggingAccess ControlClient ScriptDevelopment ToolsTroubleshooting

Business Rules

Business Rules run on the server when records are inserted, updated, deleted, or queried. Use them for data validation, automation, and integrations.

Auto-assign Based on Category

Automatically assign tickets to the appropriate assignment group based on category.

Table: incident When: before
auto-assignassignment-groupcategorybeforeinsertupdate

Send Email Notifications

Send customized email notifications when specific conditions are met.

Table: incident When: after
emailnotificationafterinsertupdateglideemailoutbound

Populate Fields on Insert

Automatically populate fields with default values or calculated values when a record is created.

Table: incident When: before
auto-populatedefault-valuesinsertbeforeinitialization

Prevent Duplicate Records

Check for existing records and prevent duplicates based on specific field combinations.

Table: incident When: before
duplicate-preventionvalidationbeforeinsertdata-quality

Cascade Status Updates

Automatically update related records when the parent record status changes (e.g., resolve all child tasks when parent is resolved).

Table: incident When: after
cascaderelated-recordsstatus-updateafterupdateautomation

Create Related Records

Automatically create related records when certain conditions are met (e.g., create change request when major incident is detected).

Table: incident When: after
create-recordsautomationchange-requestafterinsertrelated-records

Calculate and Update SLA

Automatically calculate SLA due dates based on priority, business hours, and update SLA status.

Table: incident When: before
sladue-dateschedulecalculationbeforeinsertupdatebusiness-hours

Create Approval Records

Automatically create approval records and request approvals when certain conditions are met (e.g., high-cost purchases, major changes).

Table: change_request When: after
approvalworkflowafterinsertupdatesysapproval_approverautomation

Audit Trail and Change Logging

Create detailed audit trail records when sensitive fields are modified, maintaining compliance and tracking changes.

Table: incident When: after
auditloggingcompliancetrackingafterupdatechange-historysecurity

Integrate with External System (Webhook)

Send data to external systems via REST API webhooks when records are created or updated (e.g., Slack, Teams, third-party systems).

Table: incident When: async
integrationwebhookrest-apiexternal-systemasyncinsertupdateslackteams

Query Business Rule - Restrict Visible Records

Limit which records users can see based on custom criteria like location, department, or assignment group membership.

Table: incident When: before
querybeforesecuritydata-filteringrbacrow-level-security

Display Business Rule - Calculate Values

Calculate and display values on forms without modifying the database, useful for showing metrics, totals, or derived information.

Table: incident When: display
displaycalculated-fieldsmetricsread-onlyperformanceaggregation

Async Notification with Complex Conditions

Send notifications asynchronously based on complex business logic, preventing delays in record save operations.

Table: incident When: async
asyncnotificationemailalertingescalationinsertupdatecomplex-logic

Cascade Update to Child Records

Automatically update related child records when parent record changes, maintaining data consistency across relationships.

Table: incident When: after
afterupdatecascadeparent-childrelationshipsdata-syncautomation

Auto-numbering with Custom Prefix

Generate custom record numbers with prefixes based on category, type, or other fields (e.g., HW0001, SW0002, NET0003).

Table: incident When: before
beforeinsertauto-numberingcustom-numberingsequenceprefixformatting

Service Catalog Auto-Create Fulfillment Tasks

Automatically create fulfillment tasks for specific catalog items when requests are submitted, enabling multi-step approval and delivery workflows.

Table: sc_req_item When: after
service-catalogfulfillmentautomationtasksworkflowafterinsertsc_req_itemdependencies

CMDB Data Governance Analyzer

Type: Business Rule Table: cmdb_ci
CMDBData GovernanceComplianceBusiness RulesQualityConfiguration Management

Script Includes

Script Includes contain reusable server-side code that can be called from Business Rules, other Script Includes, or client-side via GlideAjax.

GlideAjax Response Handler

Provide server-side functions that can be called from Client Scripts via GlideAjax.

glideajaxajaxclient-callableuser-infometrics

Date/Time Utilities

Reusable functions for date and time calculations and formatting.

datetimedatetimeutilitiesformattingbusiness-daysschedule

User and Group Utilities

Reusable functions for user and group operations.

usergrouputilitiesrolesmanager-chainon-call

String Manipulation Utilities

Reusable functions for string operations and text processing.

stringutilitiesformattingvalidationemailphonetext-processing

Data Validation Utilities

Reusable functions for validating data and enforcing business rules.

validationdata-qualitybusiness-rulesutilitiesrequired-fieldsdate-range

GlideRecord Helper Functions

Simplified and safe GlideRecord operations with error handling.

gliderecordutilitiesquerycruddatabaseerror-handling

REST API Client Utilities

Reusable functions for making REST API calls to external systems with error handling and authentication.

rest-apiintegrationhttpexternal-apiutilitieswebhookauthentication

CMDB Utilities

Reusable functions for working with Configuration Items (CIs) in the CMDB.

cmdbconfiguration-itemscirelationshipsutilitiesimpact-analysis

GlideAjax Utility with Multiple Functions

A comprehensive Script Include demonstrating multiple client-callable functions in a single utility class.

glideajaxajaxclient-callableutilitiesvalidationsearchmulti-function

Date Calculation Utility

Reusable functions for common date and time calculations, business days, and formatting.

date-timeutilitiesbusiness-dayscalculationsformattingschedule

String Manipulation Utility

Reusable functions for common string operations, formatting, and transformations.

stringutilitiesformattingvalidationtext-processingmanipulation

REST API Response Helper

Standardized functions for formatting and handling REST API responses with consistent error handling.

rest-apiapiresponse-formattingerror-handlingscripted-restweb-services

Scheduled Job Utility Framework

Comprehensive framework for scheduled maintenance tasks including data cleanup, notifications, system health checks, and automated maintenance operations.

scheduled-jobsmaintenancecleanupnotificationshealth-checkslaautomationsystem-admin

Record Query Utility

Efficient GlideRecord query patterns with built-in best practices, error handling, and common operations.

gliderecordquerydatabaseutilitiescrudpaginationbatch-operations

ACL Performance Analyzer

Type: Script Include Table: sys_security_acl
SecurityPerformanceACLOptimizationScript IncludesDebuggingSecurity

UI Actions

UI Actions are buttons, links, and context menu items that appear on forms and lists. Use them to provide custom functionality and improve user workflows.

Bulk Update Selected Records

Add a list button to update multiple selected records at once with custom logic.

Type: List Button Table: incident
ui-actionlist-buttonbulk-updateclientglideajax

Copy Record Button

Add a form button to create a copy of the current record with all field values.

Type: Form Button Table: incident
ui-actionform-buttoncopy-recordserver-sideduplicate

Export Record to PDF

Add a form button to export the current record to a PDF document.

Type: Form Button Table: incident
ui-actionform-buttonpdfexportprintclient

Send for Approval Button

Add a form button to trigger approval workflow with validation.

Type: Form Button Table: change_request
ui-actionform-buttonapprovalworkflowvalidationserver-side

Show Related Records

Add a form button to open a popup showing related records from another table.

Type: Form Button Table: incident
ui-actionform-buttonrelated-recordspopupdialogclient

Bulk Update Selected Records (List Action)

Update multiple selected list records with custom field values, useful for mass updates.

Type: List Button Table: incident
ui-actionlist-buttonbulk-updatemass-updateserver-sidelist-action

Export to CSV (List Action)

Export selected list records to CSV file with custom field selection.

Type: List Button Table: incident
ui-actionlist-buttonexportcsvexcelserver-sidedownload

Clone Record with Related Items

Deep copy a record including related child records like tasks, attachments, and notes.

Type: Form Button Table: incident
ui-actionform-buttonclonecopydeep-copyrelationshipsserver-side

Manually Trigger Approval Process

Trigger a custom approval workflow with validation and user selection of approvers.

Type: Form Button Table: change_request
ui-actionform-buttonapprovalworkflowcabserver-sidechange-management

Bulk Status Transition with Validation

Type: UI Action Table: incident
Bulk OperationsUI ActionState TransitionAutomationWorkflowOperationsPerformance

Scheduled Jobs

Automated background jobs that run on defined schedules to perform maintenance, data processing, and system health checks.

Audit Log Archive Manager

Archives old audit records to a history table and purges entries beyond the retention window to maintain system performance.

Table: sys_audit
auditcleanupmaintenanceperformanceretentionscheduled-job

CMDB Health Monitor and Compliance Auditor

Type: Scheduled Job Table: cmdb_ci
CMDBData QualityScheduled JobsMonitoringComplianceITOMHealth CheckReporting

Fixit Task Generator

Type: Scheduled Job Table: task
FixitAutomationTask GenerationRemediationSLAEscalationScheduled JobsOperations

Fixit Task Generator

Type: Scheduled Job Table: task
FixitAutomationTask GenerationRemediationSLAEscalationScheduled JobsOperations

Incident Surge Analyzer

Type: Scheduled Job Table: incident
Incident ManagementSLAProactive MonitoringSurge DetectionScheduled JobsOperationsAnalytics

Record Lock Monitor and Auto-Release

Type: Scheduled Job Table: sys_metadata
Lock ManagementSession MonitoringData IntegrityAutomationScheduled JobsOperationsSecurity

Health Check & Auto-Remediation Scheduler

Type: Scheduled Job Table: sysevent
Health CheckAuto-RemediationScheduled JobsOperationsAutomationMonitoringData QualityMaintenance

Orphaned Attachment Cleaner

Type: Scheduled Job Table: sys_attachment
CleanupMaintenanceScheduled JobsStorageAttachmentsDatabaseOperationsAudit

Batch Data Validator and Repair Tool

Type: Scheduled Job Table: sys_transaction
Data QualityValidationCleanupRepairScheduled JobsDatabaseIntegrityAutomation