script to assign random user from user table to another table field in servicenow
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-20-2024 11:00 PM
Need Business rule script to assign random user from user table to another table field in servicenow
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-20-2024 11:41 PM
Not sure why you keep on refusing to provide any information that makes it easy to help you.
I can't provide anything else then this with you very limited explanation:
// Query the vendor table to get all users
var vendorList = new GlideRecord('u_vendor');
vendorList.query(); // Add any conditions if needed
var userList = [];
while (vendorList.next()) {
// Assuming 'user' is the field that contains the user reference in the vendor table
userList.push(vendorList.getValue('user'));
}
if (userList.length > 0) {
// Generate a random index
var randomIndex = Math.floor(Math.random() * userList.length);
// Select a random user from the list
var selectedUser = userList[randomIndex];
// Update the engagement table
var engagementRecord = new GlideRecord('u_engagement'); // Replace 'u_engagement' with your actual engagement table name
engagementRecord.initialize();
engagementRecord.setValue('assigned_to', selectedUser); // Replace 'assigned_to' with the actual field name where you want to set the user
// Set other necessary fields for the engagement record here
engagementRecord.insert();
gs.info('Random user assigned to engagement: ' + selectedUser);
} else {
gs.warn('No users found in the vendor table.');
}
Please mark any helpful or correct solutions as such. That helps others find their solutions.
Mark
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-20-2024 11:45 PM
You can use math.random
var userSys_id;
var userCount = 'max no of user that can be in the table'
var random = Math.floor((Math.random() * userCount));
var rec = new GlideRecord('sys_user'); //you can use any table name with user data
rec.addQuery('active', true);
rec.setLimit(random);
rec.query();
while (rec.next()) {
if (!rec.hasNext()) {
userSys_id = rec.getValue('sys_id'); // you can use this sys_id to further assign the user in another table record
}
}
Regards,
Piyush Sain
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎02-21-2024 12:00 AM
Hi @Nandhini Sri ,
If it is just any random user you can just simply query user table with setLimit(1) and keep assigning that user to the engagement table.
Or You can create a dummy user only for this purpose and keep using that users sys_id to assign.
This way you improve the performance as well.