script-execution
Safe background script execution patterns including automated execution via sys_trigger, fix script generation, error handling, and logging best practices
Happy Technologies LLC · Static checks on file
Installation
Read the source and dependencies before running a command. Copying does not install or execute anything.
npx skills add Happy-Technologies-LLC/happy-platform-skills --skill script-executionAbout this skill
name: script-execution version: 1.0.1 description: Safe background script execution patterns including automated execution via sys_trigger, fix script generation, error handling, and logging best practices author: Happy Technologies LLC tags: [admin, scripts, automation, sys-trigger, fix-scripts, debugging, development] platforms: [claude-code, claude-desktop, chatgpt, cursor, any] tools: mcp: - SN-Execute-Background-Script - SN-Create-Fix-Script - SN-Query-Table - SN-Create-Record rest: - /api/now/table/sys_trigger - /api/now/table/syslog - /api/now/table/sys_script_fix native: - Bash - Read complexity: advanced estimated_time: 10-30 minutes
Script Execution
Overview
This skill covers safe and effective execution of background scripts in ServiceNow:
- Automated script execution via sys_trigger (the breakthrough method)
- Safe script patterns and templates
- Fix script generation for manual execution
- Error handling and logging best practices
- Debugging and troubleshooting techniques
When to use: When MCP tools don't support the required operation, or when complex data manipulation is needed.
Who should use this: Administrators and developers who need to execute server-side JavaScript in ServiceNow.
Prerequisites
- Roles:
admin(background script execution requires full admin) - Access: sys_trigger, syslog, sys_script_fix tables
- Knowledge: GlideRecord API, ServiceNow server-side JavaScript
- Caution: Background scripts run with elevated privileges - test carefully
Execution Methods
Method Comparison
| Method | Automation | Speed | Use Case |
|---|---|---|---|
| sys_trigger | Full | ~1-2 sec | Preferred for all automated tasks |
| UI endpoint | Full | ~1-2 sec | Fallback if trigger fails |
| Fix Script | Manual | Variable | Audit trail, scheduled execution |
| Scripts - Background | Manual | Immediate | One-time interactive testing |
Procedure
Phase 1: Automated Execution (Recommended)
Step 1.1: Basic Script Execution
The sys_trigger method creates a scheduled job that executes immediately and self-deletes.
Using MCP:
Tool: SN-Execute-Background-Script
Parameters:
script: |
gs.info('Hello from automated script execution!');
// Your logic here
var count = 0;
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.addQuery('priority', 1);
gr.setLimit(10);
gr.query();
while (gr.next()) {
count++;
gs.info('Found P1 incident: ' + gr.number);
}
gs.info('Total P1 incidents found: ' + count);
description: Count active P1 incidents
execution_method: trigger
How It Works:
- Creates a scheduled job in
sys_triggertable - Sets next_action to run immediately
- Trigger executes the script
- Script logs output to system logs
- Trigger auto-deletes after execution
Step 1.2: Verify Execution
Check System Logs:
Tool: SN-Query-Table
Parameters:
table_name: syslog
query: message=*automated script*^sys_created_on>javascript:gs.minutesAgo(5)
fields: message,level,sys_created_on,source
limit: 20
Log Levels:
| Level | Method | Purpose |
|---|---|---|
| 0 | gs.info() | Informational messages |
| 1 | gs.warn() | Warning messages |
| 2 | gs.error() | Error messages |
| 3 | gs.debug() | Debug messages (if enabled) |
Phase 2: Safe Script Patterns
Step 2.1: Query Pattern (Read-Only)
Safe pattern for reading data:
Tool: SN-Execute-Background-Script
Parameters:
script: |
// Safe read-only pattern
var results = [];
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.addQuery('priority', 1);
gr.setLimit(100); // Always set a limit
gr.query();
while (gr.next()) {
results.push({
number: gr.number.toString(),
short_description: gr.short_description.toString(),
assigned_to: gr.assigned_to.getDisplayValue(),
created: gr.sys_created_on.toString()
});
}
gs.info('Query Results: ' + JSON.stringify(results, null, 2));
description: Query active P1 incidents (read-only)
Step 2.2: Update Pattern (With Safety Checks)
Pattern for updating records with safety measures:
Tool: SN-Execute-Background-Script
Parameters:
script: |
// Safe update pattern with validation
var TABLE = 'incident';
var QUERY = 'active=true^priority=1^assigned_toISEMPTY';
var MAX_UPDATES = 10; // Limit updates per execution
// DRY RUN flag - set to false to actually update
var DRY_RUN = true;
var updated = 0;
var skipped = 0;
var gr = new GlideRecord(TABLE);
gr.addEncodedQuery(QUERY);
gr.setLimit(MAX_UPDATES);
gr.query();
gs.info('Found ' + gr.getRowCount() + ' records to process');
while (gr.next()) {
// Validate before update
if (!gr.canWrite()) {
gs.warn('Cannot write to: ' + gr.number);
skipped++;
continue;
}
if (DRY_RUN) {
gs.info('[DRY RUN] Would update: ' + gr.number);
} else {
gr.work_notes = 'Automated: Escalating unassigned P1';
gr.assignment_group = 'Critical Incidents Team';
gr.update();
gs.info('Updated: ' + gr.number);
updated++;
}
}
gs.info('Summary: Updated=' + updated + ', Skipped=' + skipped + ', DryRun=' + DRY_RUN);
description: Escalate unassigned P1 incidents (with dry run)
Step 2.3: Insert Pattern (With Duplicate Check)
Pattern for creating records safely:
Tool: SN-Execute-Background-Script
Parameters:
script: |
// Safe insert pattern with duplicate check
var TABLE = 'sys_properties';
var PROPERTY_NAME = 'custom.automation.enabled';
var PROPERTY_VALUE = 'true';
// Check for existing
var existing = new GlideRecord(TABLE);
existing.addQuery('name', PROPERTY_NAME);
existing.query();
Read the complete source ↗