script to delete inactive user list
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-30-2024 09:33 AM
Hi,
I have created business rule to check for inactive user into assigned_to field from the table(cmdb_ci), and delete from all applicable assigned_to fields. pls let me know the correction in the script:
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-30-2024 09:59 AM
Hi @BanuMahalakshmi Try below code
// Initialize a GlideRecord for the cmdb_ci table
var gr = new GlideRecord("cmdb_ci");
// Ensure we only retrieve records where the assigned_to field is not empty
gr.addQuery("assigned_to", "!=", "");
gr.query();
// Array to keep track of inactive user IDs
var inactiveUsers = [];
// Iterate over each record in cmdb_ci
while (gr.next()) {
// Split the assigned_to field into an array if it's a comma-separated list
var assignedToArray = gr.assigned_to.toString().split(",");
// Iterate over each user in the assigned_to field
for (var i = 0; i < assignedToArray.length; i++) {
// Initialize a new GlideRecord for the sys_user table
var usr = new GlideRecord("sys_user");
// Check if the user record exists
if (usr.get(assignedToArray[i])) {
// Check if the user is inactive
if (!usr.active) {
// Add the inactive user ID to the array
inactiveUsers.push(usr.sys_id.toString());
// Remove the inactive user from the assigned_to field
assignedToArray.splice(i, 1); // Remove the inactive user from the array
i--; // Adjust the index due to array modification
}
} else {
gs.log("User not found: " + assignedToArray[i]);
}
}
// Update the assigned_to field with the active users
gr.assigned_to = assignedToArray.join(",");
gr.update(); // Save changes to the cmdb_ci record
}
// Log the IDs of inactive users removed
gs.log("Inactive users removed: " + inactiveUsers.join(", "));
Regards,
Sid
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-30-2024 01:09 PM
cmdb_ci.assigned_to is a Reference field to the sys_user table, and con not contain more than one value. the above is overly complicated.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-30-2024 09:39 PM
Hi @BanuMahalakshmi , Try below code
var cmdbGr = new GlideRecord("cmdb_ci");
cmdbGr.addEncodedQuery("assigned_toISNOTEMPTY");
cmdbGr.query();
var inactiveUsers = [];
while (cmdbGr.next()) {
var userSysId = cmdbGr.assigned_to;
var usrGR = new GlideRecord("sys_user");
if (usrGR.get(userSysId)) {
if (!usrGR.active) {
inactiveUsers.push(usrGR.sys_id.toString());
cmdbGr.assigned_to = '';
cmdbGr.update(); // Save changes to the cmdb_ci record
}
} else {
gs.log("User not found: " + userSysId);
}
}
gs.log("Inactive users removed: " + inactiveUsers.join(", "));
Thanks,
BK