The gs Object in ServiceNow: Complete Method Reference

gs is the GlideSystem object — the global utility available in every server-side script in ServiceNow. Business Rules, Script Includes, Scheduled Jobs, REST API scripts — gs is always available. This reference covers every method you will actually use in production, organised by category, with examples.

Logging methods

Always pass a source identifier as the second argument — it makes filtering the system log fast and reliable. See the debugging guide for how to use these effectively.

gs.log('General message');                    // Info level — System Log
gs.log('Processing record', 'MyScriptName'); // With source — filterable
gs.info('Processing started', 'MyScript');   // Info level
gs.warn('Queue depth high', 'JobMonitor');   // Warning level
gs.error('Failed to process', 'MyScript');   // Error level
gs.debug('Step complete', 'MyScript');       // Debug — visible when session debug enabled

User context

gs.getUserID();                  // sys_id of currently logged-in user
gs.getUserName();                // Username (login name) e.g. "john.smith"
gs.getUser().getFullName();      // Display name e.g. "John Smith"
gs.getUser().getEmail();         // User's email address
gs.hasRole('itil');              // Boolean — does current user have this role?
gs.hasRole('itil,admin');        // Boolean — has either role (OR, not AND)
gs.isInteractive();              // True if user is in browser session (not API/background)
gs.getSession().isInteractive(); // Same as above
gs.getSession().getClientIP();   // Client IP address

For more on roles and how they work, see Roles vs Groups in ServiceNow. For getUserID patterns in scripts and ACLs, see gs.getUserID() complete reference.

Date and time utilities

gs.now();                         // Current datetime as UTC string: "2026-05-13 14:30:00"
gs.nowDateTime();                 // GlideDateTime of current time
gs.beginningOfToday();            // Start of today in local time
gs.endOfToday();                  // End of today in local time
gs.beginningOfThisWeek();         // Monday 00:00 of this week
gs.endOfThisWeek();               // Sunday 23:59 of this week
gs.beginningOfThisMonth();        // First day of this month 00:00
gs.endOfThisMonth();              // Last day of this month 23:59
gs.beginningOfLastMonth();        // First day of last month
gs.endOfLastMonth();              // Last day of last month
gs.beginningOfThisQuarter();      // Start of current quarter
gs.beginningOfThisYear();         // Jan 1 of current year
gs.daysAgo(7);                    // datetime 7 days ago
gs.daysAgoStart(7);               // start of day 7 days ago (for range queries)
gs.daysAgoEnd(0);                 // end of today (for range queries)
gs.hoursAgo(24);                  // datetime 24 hours ago
gs.minutesAgo(30);                // datetime 30 minutes ago

System properties

// Read a system property
gs.getProperty('glide.ui.home');                          // Returns value or null
gs.getProperty('my.setting', 'default_value');            // Returns default if not found

// Set a system property (requires admin role)
gs.setProperty('my.setting', 'new_value');
gs.setProperty('my.setting', 'new_value', 'Description'); // With description

// Check before using
var endpoint = gs.getProperty('my.api.endpoint');
if (!endpoint) {
    gs.error('System property my.api.endpoint is not configured', 'MyIntegration');
    return;
}

For the full gs.getProperty() reference including type handling and caching, see gs.getProperty() complete reference.

Event management

// Queue an event that fires a notification or Script Action
gs.eventQueue(
    'incident.priority.changed',  // Event name (must exist in Event Registry)
    current,                       // GlideRecord object (event source)
    current.getValue('assigned_to'), // param1
    current.getValue('priority')     // param2
);

// Schedule event for future execution
gs.eventQueueScheduled(
    'event.name',
    current,
    param1,
    param2,
    'tomorrow'  // Run time: 'tomorrow', 'next week', or GlideDateTime string
);

// Check if an event is queued
var isQueued = gs.eventQueuedAlready('incident.priority.changed', current);

String and encoding utilities

gs.generateGUID();                  // Generate a new 32-char sys_id
gs.urlEncode('hello world');        // "hello+world"
gs.urlDecode('hello+world');        // "hello world"
gs.base64Encode('my string');       // Base64 encoded string
gs.base64Decode('bXkgc3RyaW5n');   // Decoded string
gs.xmlToJSON(xmlString);            // Convert XML string to JavaScript object
gs.jsonToXML(jsonObject);           // Convert object to XML string
gs.htmlDecode('<b>');            // Decode HTML entities

Number formatting

gs.getProperty('glide.currency.code', 'USD'); // Instance currency code

// Format a number with locale settings
// Note: for currency/number display, GlideLocale is typically used
// gs provides basic utilities

Session and context

gs.getSession();                        // GlideSession object
gs.getSession().putClientData('key', 'value'); // Store value in session
gs.getSession().getClientData('key');   // Retrieve from session (string)
gs.getCurrentApplicationID();          // Current application scope sys_id
gs.getCurrentApplicationName();        // Current application scope name
gs.getMaxSchemaNameLength();            // Max table/column name length
gs.getNodeName();                       // Name of current node in cluster

Impersonation utilities

// Check if currently running as background/system
if (!gs.isInteractive()) {
    // Running via API, Scheduled Job, or background script
    gs.log('Non-interactive session — skipping UI checks', 'MyScript');
}

// Get the real user when impersonating
gs.getImpersonatingUserName(); // Returns username being impersonated, or null
gs.getImpersonatingUserDisplayName(); // Display name of impersonated user

Table and schema utilities

// Check if a table exists
var tableExists = gs.tableExists('my_custom_table');

// Check if a record exists by sys_id
var recExists = gs.recordExists('incident', sys_id);

// Get the display name of a table
gs.getTableDisplayName('incident'); // Returns "Incident"

Sending emails programmatically

// Send a simple email from a script
var email = new GlideEmailOutbound();
email.setSubject('Incident Alert: ' + current.getValue('number'));
email.setBody('A new P1 incident has been created: ' + current.getValue('short_description'));
email.addRecipient(current.assigned_to.getDisplayValue());
email.addAddress('to', 'manager@company.com');
email.save();

Password and security utilities

gs.generateGUID();  // Use for generating sys_ids or unique keys
// For generating passwords:
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var password = '';
for (var i = 0; i < 12; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length));
}

Related scripting guides:

gs.log(), gs.info(), gs.warn(), gs.error() — logging methods

The gs logging methods write to the System Log and are your primary debugging and operational logging tool for server-side scripts. They differ in severity level and visibility:

// gs.log(message, source) — general purpose
gs.log('Processing complete: ' + recordCount + ' records updated', 'DailyJob');

// gs.info(message, source) — informational, lower noise
gs.info('Integration sync started', 'SAPConnector');

// gs.warn(message, source) — something unexpected but non-fatal
gs.warn('User not found for email: ' + emailAddress, 'UserProvisioning');

// gs.error(message, source) — error condition, always visible
gs.error('Failed to call external API: ' + errorMsg, 'IntegrationHandler');

// Without source parameter — source shows as empty string
gs.log('Simple debug message');

The source parameter (second argument) is critical for production code — it lets you filter the System Log by your component name. Always provide a source string in any Script Include or Scheduled Job that could generate log volume. In Scripts - Background debugging sessions, the source can be anything descriptive.

gs.getProperty() and gs.setProperty()

// Read a system property (second arg is default if property doesn't exist)
var maxRetries = parseInt(gs.getProperty('my_app.integration.max_retries', '3'));
var apiEndpoint = gs.getProperty('my_app.api.base_url', 'https://api.example.com');

// Set a property programmatically (admin rights required)
gs.setProperty('my_app.last_sync_time', gs.nowDateTime());

// Check property existence
var endpoint = gs.getProperty('my_app.endpoint');
if (!endpoint) {
    gs.error('Required property my_app.endpoint is not configured', 'MyApp');
    return;
}

System properties are the correct mechanism for externalising configuration from scripts. API endpoints, feature flags, threshold values, email addresses — anything that varies between environments or might need to change without a code deployment should be a system property. Never hardcode these values in scripts. See the gs.getProperty deep dive for more on property management patterns.

gs.getUserID(), gs.getUserName(), gs.getUser()

// Get current user's sys_id
var userId = gs.getUserID(); // returns sys_id string

// Get current user's username (login name, not display name)
var username = gs.getUserName(); // "john.smith", not "John Smith"

// Get the full GlideUser object (more expensive — use when you need user attributes)
var user = gs.getUser();
var firstName = user.getFirstName();
var email = user.getEmail();
var companyId = user.getCompanyID();

// Check if user has a specific role
if (gs.hasRole('admin')) {
    // Show admin-only features
}
if (gs.hasRole('itil') || gs.hasRole('x_myapp.editor')) {
    // User has either the platform itil role or the custom app editor role
}

In Business Rules and ACL scripts, gs.getUserID() runs as the user who triggered the operation. In Scheduled Jobs, it runs as the admin user configured for the job. Understanding whose context gs.getUserID() returns — and when it might return the system user vs a real user — is important for building scripts that behave correctly across both interactive and automated contexts.

gs.now(), gs.nowDateTime(), gs.daysAgo()

// Current date as YYYY-MM-DD
var today = gs.now();  // "2026-05-15"

// Current datetime as YYYY-MM-DD HH:MM:SS (UTC)
var now = gs.nowDateTime();  // "2026-05-15 14:30:00"

// Date utility methods for queries
var sevenDaysAgo = gs.daysAgo(7);         // date 7 days ago
var startOfMonth = gs.beginningOfThisMonth();
var endOfMonth = gs.endOfThisMonth();
var startOfWeek = gs.beginningOfThisWeek();

// Using in encoded queries
var recentQuery = 'opened_at>' + gs.daysAgo(30);
gr.addEncodedQuery(recentQuery);

// Or with the javascript: syntax in encoded queries
// 'opened_atONThis month@javascript:gs.beginningOfThisMonth()@javascript:gs.endOfThisMonth()'

gs.include() — loading Script Includes

Script Includes load automatically when you instantiate them with new ScriptIncludeName(). You rarely need gs.include() directly. The exception: loading utility libraries that are not instantiated as classes — older-style Script Includes that expose functions rather than a class. Modern development practice uses class-based Script Includes; if you encounter gs.include() in legacy code, it is loading a functional Script Include.

gs in Client Scripts — the restriction

The gs object is a server-side only API. It is not available in Client Scripts or UI Scripts. Client Scripts have a different global context with different available APIs — g_form, g_user, GlideAjax. If you see gs.getProperty() in a Client Script, it will silently fail or throw an error. The pattern for making server-side data available to client scripts is either g_scratchpad in a Display Business Rule or a GlideAjax call to a Script Include that uses gs.

Related scripting guides: gs.getProperty · gs.getUserID · GlideRecord · Business Rules · Debugging

gs as the backbone of server-side scripting

The gs object is present in every server-side script context — Business Rules, Script Includes, Scheduled Jobs, ACL Scripts, UI Actions, and Processors. It is the Swiss Army knife of ServiceNow scripting: user context, logging, property access, date utilities, session information, and more. Fluency with gs methods is a prerequisite for fluency with any server-side ServiceNow scripting. Developers who know the full gs API — not just gs.log() and gs.getUserID() but also gs.getSession(), gs.isInteractive(), gs.getImpersonatingUserName() — write noticeably tighter, more contextually-aware scripts. Study the full gs object reference alongside the GlideRecord API for a complete picture of what is available in every server-side script context. The technical interview questions frequently test gs method knowledge alongside GlideRecord patterns. Make the gs API reference part of your regular study materials, revisit it when you encounter edge cases in production scripting, and build fluency through practice rather than memorisation.

50 scripting patterns in one guide

The NowSpectrum Pro Tips and Tricks guide covers 50 battle-tested patterns including gs methods, GlideRecord, Script Includes, and debugging techniques.

Get the Pro Tips Guide →
← Back to all posts