diff --git a/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Inserting new record to User Table.js b/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Inserting new record to User Table.js new file mode 100644 index 0000000000..f09f582965 --- /dev/null +++ b/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Inserting new record to User Table.js @@ -0,0 +1,39 @@ +var userData = { + user_name: 'hackfest.user', // Demo Data only we can change whatever as we need + first_name: 'Hack', // Demo Data only we can change whatever as we need + last_name: 'Fest', // Demo Data only we can change whatever as we need + email: 'hackfest.user@servicenow.com'// Demo Data only we can change whatever as we need +}; + +// Check if mandatory fields are present +if (!userData.user_name || !userData.first_name || !userData.last_name || !userData.email) { + gs.info('Missing required fields. User not created.'); +} else { + // Check if user already exists to avoid duplicates + var grCheck = new GlideRecord('sys_user'); + grCheck.addQuery('user_name', userData.user_name); + grCheck.query(); + + if (grCheck.next()) { + gs.info('User [' + userData.user_name + '] already exists.'); + } else { + // Initialize new GlideRecord for sys_user + var gr = new GlideRecord('sys_user'); + gr.initialize(); + + // Dynamically set all fields from the object + for (var field in userData) { + if (gr.isValidField(field)) { + gr[field] = userData[field]; + } + } + + // Insert record + var newUserSysId = gr.insert(); + if (newUserSysId) { + gs.info('User [' + userData.user_name + '] created successfully. Sys ID: ' + newUserSysId); + } else { + gs.info('Failed to create user [' + userData.user_name + ']'); + } + } +} diff --git a/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Readme.md b/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Readme.md new file mode 100644 index 0000000000..f5b9f72eef --- /dev/null +++ b/Server-Side Components/Background Scripts/inserting a new record into the sys_user table/Readme.md @@ -0,0 +1,18 @@ +ServiceNow User Creation Script: +Overview: + +This script allows you to create a new user in the sys_user table of your ServiceNow instance. It performs checks to ensure mandatory fields are present and avoids creating duplicate users based on the user_name. + +It is designed to be directly run in Background Scripts and is easy to adapt for creating multiple users or adding additional fields. + +Features: + +Dynamically sets field values from a JavaScript object. + +Checks that all mandatory fields (user_name, first_name, last_name, email) are provided. + +Avoids duplicates by checking if the user_name already exists. + +Provides clear logs in the system for success or failure. + +Fully compatible with Background Scripts.