# Advanced Scripting and Workflows

> Chapter 9 of the Courseiva SERVICENOW-CAD curriculum — https://courseiva.com/learn/servicenow-cad/advanced-scripting-workflows

**Official objective:** 4.2 — Implement complex business logic using advanced scripting and scheduled jobs

## Introduction

Advanced scripting and workflows let you automate decisions and processes that would otherwise require a human to click through dozens of steps. For a business, this means tasks like resetting passwords, approving requests, or updating records happen instantly and consistently. As a SNOW-CAD candidate, you must understand how to write scripts that run automatically on schedules or in response to events, and how to design workflows that manage complex approval chains.

## The Head Chef's Recipe Book Analogy

A professional kitchen's recipe book is not a list of simple tasks; it is a collection of advanced instructions for complex dishes. Each recipe contains conditional steps, timers for scheduled preparation, and sub-recipes that run automatically. The head chef does not stand at every station shouting orders; they design the systems so that when a ticket arrives, the right steps execute at the right time without constant oversight.

In the same way, advanced scripting and workflows in ServiceNow allow you to write coded instructions that automate multi-step processes, handle decisions based on data, and schedule actions for later execution. A scheduled job is like setting a slow-cooker timer: you tell the system to run a specific script at 2 AM every day, and it does the work while you sleep. A workflow is like a cooking sequence: first chop, then sauté, then simmer, with checks at each stage to ensure the dish comes out right. The complex logic you write replaces manual intervention, reduces errors, and scales across thousands of records. Just as a kitchen runs smoothly when recipes are well-designed, a ServiceNow instance runs efficiently when scripting and workflows are properly implemented.

## Core explanation

Advanced scripting in ServiceNow is the practice of writing JavaScript code to extend the platform's capabilities beyond what configuration alone can achieve. A script is simply a set of instructions written in a programming language that the computer executes. In ServiceNow, scripts are written in JavaScript, a language widely used on the web. You use scripts to perform calculations, manipulate data, interact with external systems via REST APIs (which are standardised ways for applications to talk to each other over the internet), and control the flow of business logic.

Workflows, on the other hand, are visual representations of a multi-step process. Each step in a workflow can be a manual task (like sending an approval request to a manager), an automated action (like updating a field), or a condition that branches the flow based on data. Workflows are built using the Workflow Editor, a drag-and-drop interface that generates the underlying script automatically. However, the platform also allows you to insert custom scripts within workflow activities for advanced logic.

Scheduled jobs are scripts that run at predetermined times. They are created under the Scheduled Jobs module. You configure a trigger: once, daily, weekly, monthly, or using a cron expression (a text string that defines precise timing, e.g. "0 2 * * *" means 2 AM every day). When the trigger fires, the script executes. This replaces tasks like manually running a report every Monday morning or sending a summary email at month-end.

Why do we need all this? Before these capabilities, IT teams had to perform repetitive tasks manually, which was slow, error-prone, and expensive. Scripting and workflows automate these tasks, ensuring consistency and freeing up humans for more strategic work. For example, an IT department might have a workflow that runs when a new employee is hired: it creates a user account, assigns role-based access, orders equipment, and sends a welcome email. Without a workflow, someone would have to remember to do each step.

The key components you need to know are:

- Business Rules: scripts that run on database operations (insert, update, delete, query) before or after the action. They enforce logic like "when a ticket is closed, set the resolved date to now".
- Script Includes: reusable functions that you can call from any other script. They help you avoid repeating code. Define a function once, use it hundred times.
- Client Scripts: scripts that run in the user's browser, providing instant feedback like validating a form field without waiting for the server.
- Workflow Activities: pre-built actions like 'Send Email', 'Approval', 'Run Script', 'Timer'. You connect them in a sequence.
- Scheduled Jobs: scripts triggered by time, not by a user action.

All these tools use GlideRecord, the ServiceNow API for querying and modifying database tables. A GlideRecord query is like writing a search query: you specify the table (e.g., 'incident'), add conditions (e.g., state = 'new'), and then loop over the results to perform actions. For example:

var gr = new GlideRecord('incident');
gr.addQuery('state', 'new');
gr.query();
while (gr.next()) {
    gr.state = 'in_progress';
    gr.update();
}

This script finds every incident with state 'new', changes its state to 'in_progress', and saves the change. Without advanced scripting, you would have to open each ticket manually.

When building complex business logic, you must also understand condition evaluation. ServiceNow allows you to write conditions using scripts or a simple condition builder. For example, an approval rule might say: "if the requested item costs more than £1,000, require director approval". This is a conditional workflow branch. The condition is evaluated when the record reaches that point in the workflow.

Scope is an important concept. When you write a script, variables you declare within a function or activity are local to that context. If you need to share data between workflow activities, you use workflow scratchpad variables (a temporary storage area). Similarly, when writing a scheduled job, be careful with scoping: each run is independent.

Error handling is also critical. Scripts can fail due to network timeouts, invalid data, or permission errors. Use try-catch blocks to catch errors gracefully and log them. The gs.log() function writes messages to the system log for debugging. You can also use gs.addErrorMessage() to display an error to the user if the script runs in an interactive context.

Finally, performance matters. A badly written script can slow down the entire instance. Always filter GlideRecord queries to retrieve only the records you need. Avoid querying inside loops when you can query once and use arrays. Use indexed fields in conditions. The platform provides a Performance Dashboard to identify slow scripts, but as a developer, you should write efficient code from the start.

## Real-world context

Imagine you work as a ServiceNow developer for a large insurance company. Every week, the HR department imports a spreadsheet of 500 new employees from the payroll system. Without automation, an IT technician would have to log in, create each employee's user account, assign them to the correct department group, send a welcome email, and create a hardware order. Doing this for 500 people takes hours and almost always introduces typos.

You decide to build an automated solution using advanced scripting and workflows. Here is exactly what you do:

First, you write a scheduled job that runs every Monday at 6 AM. The script uses a GlideRecord query to pull new records from the import table (where the payroll system dumps the data). It then iterates over each record. Inside the loop, you call a custom script include called 'UserProvisioner' that contains reusable functions to create a user, assign a role, and send an email. The script include uses the GlideRecord API to create a new sys_user record, setting fields like name, email, department, and manager. It also uses the Role API to add the 'itil' role automatically.

Once the user account is created, the script triggers a workflow. It calls the workflow.startFlow() method, passing the sys_id of the new user. The workflow is called 'New Hire Onboarding'. The first step is a 'Run Script' activity that adds the user to a catalogue item group based on their department. The second step is an 'Approval' activity that sends an approval request to the IT manager if the department is 'Executive'. If approved, the workflow proceeds; if rejected, it sends a notification to HR. The third step is a 'Task' activity that creates a standard change request to order a laptop, which is assigned to the procurement team. The final step sends a welcome email to the new employee with their login credentials.

You also set up a business rule on the 'user' table. When an employee's record is updated (e.g., they change department), the business rule detects the change and runs a script that removes old group memberships and adds new ones. This ensures access rights are always up-to-date.

Additionally, you create a client script on the 'new hire request' form that validates the manager's email address format before the form is submitted. If the email is invalid, a red error message appears instantly and the form is not sent to the server. This prevents bad data from entering the workflow.

After implementation, what used to take three hours every Monday now happens in under two minutes. The error rate drops to zero. The IT technicians are freed to work on more valuable tasks, like resolving security incidents.

This scenario shows you the real power of advanced scripting and workflows: they turn manual drudgery into smooth, reliable automation. As a developer, you design the logic that makes the business run faster and better. On the SNOW-CAD exam, you will be asked to identify which scripting tool (business rule, client script, scheduled job, etc.) is appropriate for a given scenario, and to recognise correct script syntax and logic flow.

## Exam focus

The SNOW-CAD exam tests your understanding of when and how to use advanced scripting tools, not your ability to memorise every function. You will see multiple-choice and drag-and-drop questions covering the following:

- Business Rules: You must know the order of execution (before vs. after, and the priority ordering within those categories). A common trap is asking which business rule runs first: the answer is the one with the lowest order value (0 being highest priority). Another trap: 'before' business rules can abort the database operation by returning false, but 'after' rules cannot.
- Script Includes: You need to understand that they are server-side and reusable. The exam often presents a scenario where you need to use the same calculation in multiple places; the correct answer is to create a script include. Trap: they might ask you to choose between a script include and a business rule when the logic is used only in one place. The correct answer is a business rule, but only if it is associated with a table operation.
- Scheduled Jobs: Expect questions about when you would use a scheduled job versus a business rule. The key difference: scheduled jobs are time-driven, business rules are event-driven. Trap: they describe a scenario where you need to run a report every Friday at 10 AM. The correct tool is a scheduled job.
- Workflow Activities: You must recognise that 'Approval' and 'Task' activities create records that can be tracked. The exam might ask you to identify which activity to use for a manual step. Trap: they will list 'Run Script' as an option for an approval request — wrong, use 'Approval'.
- GlideRecord: You will be asked to identify correct GlideRecord syntax. The most common pattern: new GlideRecord('table'), .addQuery('field', 'value'), .query(), while (.next()) { ... }. Trap: they might show code that uses .get() without a query; .get() requires a sys_id.
- Condition Builder vs. Script Condition: Know that conditions can be written using the condition builder (simple expressions) or as a script (advanced logic). The exam tests when you need a script condition — specifically, when the logic requires nested if-else or loops.
- Scope and Variables: They love to ask about the 'current' and 'previous' variables in business rules. 'current' holds the record being acted upon; 'previous' holds its values before the update. Trap: using 'previous' in a 'before' business rule — it works, but is often unnecessary because you could just check 'current' against the new values.
- Error Handling: You will see questions about try-catch blocks and gs.log(). Know that gs.log() writes to the system log for debugging and does not stop script execution.
- Performance: Questions about efficient looping. Trap: they show a script that calls .query() inside a while loop — that is inefficient and should be avoided. Correct pattern: query once, use an array.

To pass, you must be able to read script snippets and identify what they do. Practise by creating sample scripts in your own ServiceNow instance. Focus on the difference between server-side scripts (business rules, script includes, scheduled jobs) and client-side scripts (client scripts, UI policies). The exam will deliberately confuse you by describing a task that should be done on the client side but offering server-side options as traps. Remember: client scripts run in the browser and are good for validation and UI changes; server scripts run on the server and are good for data manipulation and automation.

## Step by step

1. **Define the business requirement** — Write down exactly what needs to happen: when should the script run, what data does it need, and what outcome is desired. This step prevents wasted development and ensures you choose the right tool (business rule, scheduled job, etc.).
2. **Create the script include or business rule skeleton** — Open the appropriate module (Business Rules, Script Includes, Scheduled Jobs) and create a new record. Give it a clear name and set the table if applicable. This structural step is required because ServiceNow ties scripts to a context.
3. **Write the GlideRecord query to retrieve target records** — Use .addQuery() to filter records and .query() to execute. For example, query all incidents with state 'new'. This is the core of data access in scripting, and poor queries cause performance issues.
4. **Implement the business logic inside a loop or condition** — Iterate over the retrieved records with .next() and modify fields or call other functions. Use try-catch to handle errors. This step is where the actual automation happens, changing data or triggering workflows.
5. **Test with a small data set and review system logs** — Run the script manually on a few records and check the logs using gs.log() output. Verify that the outcomes match the requirement. Testing catches syntax errors and logic bugs before the script runs in production.
6. **Set the trigger and activate the script** — For scheduled jobs, set the schedule (daily, hourly, custom cron). For business rules, set the table and order and activate it. This step makes the script run automatically in the intended conditions.

## Comparisons

### Business Rule vs Scheduled Job

**Business Rule:**
- Triggered by database events (insert, update, delete, query).
- Runs immediately when the event occurs.
- Ideal for enforcing data integrity rules in real time.

**Scheduled Job:**
- Triggered by time (once, daily, weekly, or custom cron schedule).
- Runs independently of user or data events.
- Ideal for batch processing, reports, and periodic cleanups.

### Client Script vs Business Rule

**Client Script:**
- Executes in the user's browser (client-side).
- Cannot write to the database directly.
- Used for form validation, field formatting, and UI changes.

**Business Rule:**
- Executes on the server (server-side).
- Can read and write database records.
- Used for data manipulation, automation, and enforcing business logic.

### Script Include vs Business Rule

**Script Include:**
- Reusable function library, not tied to a specific table or event.
- Called explicitly by other scripts or workflows.
- Best for encapsulating complex logic used in multiple places.

**Business Rule:**
- Tied to a specific table and database operation.
- Runs automatically without being called.
- Best for simple, single-use automation tied to data events.

### Workflow vs Business Rule

**Workflow:**
- Visual sequence of steps including approvals, tasks, and timers.
- Manages multi-step processes that require human interaction.
- Supports branches, conditions, and parallel tasks.

**Business Rule:**
- Single script that runs on a database operation.
- No visual representation; purely code-based.
- Best for simple, linear logic that does not need manual steps.

## Diagram

_Decision flow for choosing between business rules, scheduled jobs, and workflows to implement advanced scripting logic._

```mermaid
flowchart TD
    A[Business Requirement] --> B{Choose Tool}
    B --> C[Business Rule
Event-driven]
    B --> D[Scheduled Job
Time-driven]
    B --> E[Workflow
Multi-step]
    C --> F[Write Script
GlideRecord]
    D --> F
    E --> G[Design Steps
Activities]
    F --> H[Test & Log]
    G --> H
    H --> I[Activate/Deploy]
    I --> J[Automation Runs]
```

## Common misconceptions

- **Misconception:** Scheduled jobs and business rules are the same thing because both run scripts. **Reality:** They differ fundamentally: scheduled jobs run on a time trigger, while business rules run automatically in response to database events like insert or update. (Beginners see 'run script' in both contexts and think they are interchangeable, but the trigger mechanism and use cases are completely different.)
- **Misconception:** Client scripts can modify database records directly from the browser. **Reality:** Client scripts run in the user's browser and cannot write to the database. They only validate data or change UI elements. To modify records, you need a server-side script like a business rule. (This confusion arises because users see client scripts making visual changes and assume they are saving data. The security model is often not intuitive.)
- **Misconception:** You can use GlideRecord.get() to query for multiple records at once. **Reality:** GlideRecord.get() only retrieves a single record by its sys_id. To retrieve multiple records, you must use .query() and then iterate with .next(). (The word 'get' sounds like it fetches data generally, but it is specifically designed for single-record lookup by unique identifier.)
- **Misconception:** Script includes are only for ServiceNow internal use and cannot be called from workflows. **Reality:** Script includes are reusable functions that can be called from any server-side script, including workflow 'Run Script' activities. (New developers often think workflows and script includes are separate systems, but workflows can invoke script includes directly, making them powerful for complex logic.)
- **Misconception:** Error handling in a scheduled job is unnecessary because the job runs at night when no one is watching. **Reality:** Errors in scheduled jobs can cause silent failures that corrupt data or leave tasks incomplete. Using try-catch and logging is essential to detect and fix issues. (Because no user sees the error in real time, beginners assume it doesn't matter. But data integrity is critical, and debugging without logs is nearly impossible.)
- **Misconception:** Workflow 'Timer' activity waits for a human to click a button. **Reality:** A Timer activity waits for a specific duration (e.g., 24 hours) and then automatically proceeds to the next step. No human interaction is required. (The word 'Timer' sounds like a kitchen timer that you press to start, but in workflows it is a passive countdown that triggers automatically.)

## Key takeaways

- Business rules run on database events, while scheduled jobs run on time triggers.
- Client scripts validate data and change UI in the browser but cannot modify database records.
- Script includes store reusable code that reduces duplication and simplifies maintenance.
- GlideRecord.query() retrieves multiple records; .get() retrieves exactly one record by sys_id.
- Workflow activities are sequenced steps, each performing a specific action like approval or email sending.
- Use try-catch blocks in all scripts to prevent silent failures and log errors for debugging.
- The condition builder handles simple expressions, but script conditions are needed for complex logic with loops or nested if-else.
- Performance matters: always limit GlideRecord queries with filters and avoid querying inside loops.

## FAQ

**What is the difference between a business rule and a client script?**

A business rule runs on the server when a database record is inserted, updated, deleted, or queried. A client script runs in the user's browser and can validate data or change the interface, but cannot modify the database.

**How do I create a scheduled job in ServiceNow?**

Navigate to System Scheduler > Scheduled Jobs > New, choose the type (e.g., 'Run Script'), write your script, and set the trigger using conditional or time-based scheduling.

**What is GlideRecord and how do I use it?**

GlideRecord is the ServiceNow API for querying and modifying database tables. You create an object with new GlideRecord('table_name'), add conditions with .addQuery(), then call .query() to fetch records.

**Can a script include call another script include?**

Yes, script includes can call other script includes as long as they are defined and scoped correctly. It is common to have a utility script include that calls domain-specific script includes for modularity.

**How do I debug my script when it's not working?**

Use gs.log('message') to print values to the system log. You can also use gs.info() or gs.warn(). View the logs in System Logs > Application Logs. Always wrap risky code in try-catch and log the error.

**What is a workflow scratchpad and why is it used?**

A workflow scratchpad is a temporary storage area that persists data across workflow activities. It is used to pass values like a calculated approval amount or a record sys_id from one activity to another.

## Check your understanding

1. **Which tool would you use to run a script every night at 2 AM to clean up closed incidents older than 90 days?**

   Answer: A scheduled job, because it runs on a time trigger and not in response to a database event.

2. **You need to ensure that when an incident is resolved, the 'resolved_at' field is automatically set to the current date and time. Should you use a business rule or a client script?**

   Answer: A business rule, because it runs on the server when the record is updated, and can modify database fields.

3. **What is the correct method to retrieve a single record by its sys_id using GlideRecord?**

   Answer: Use .get('sys_id'), for example: new GlideRecord('incident').get('abc123').

4. **A workflow needs to wait 24 hours before proceeding. Which workflow activity should you add?**

   Answer: A Timer activity, set to a duration of 24 hours.

5. **You have a complex calculation that is used in three different business rules. What is the best way to avoid repeating the calculation code?**

   Answer: Create a script include with the calculation function, then call it from each business rule.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/servicenow-cad/advanced-scripting-workflows
