Move the Values
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-27-2024 09:11 AM
Hello @ExpertsNow
Greetings!!!
Lets say we have 2 groups in service now one is software and one is hardware so i have added users ABC in hardware group and DEF in the software. Now I would like move DEF to hardware group and ABC to the software group. How can we do that using script and What is the syntax we have to achieve this scenario.
Thanks

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-27-2024 10:00 AM
Is this a scenario you see occurring a lot? If not why not just go into the groups and manage the members that way?

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-27-2024 10:16 AM
@Krishna142 You can use the following as a fix/background script to swap users between two groups.
// Define the two group names or sys_ids you want to swap users between
var group1SysId = 'GROUP_1_SYS_ID'; // Replace with the sys_id of Group 1
var group2SysId = 'GROUP_2_SYS_ID'; // Replace with the sys_id of Group 2
// Function to get users in a group
function getUsersInGroup(groupSysId) {
var userArray = [];
var grGroupMembers = new GlideRecord('sys_user_grmember');
grGroupMembers.addQuery('group', groupSysId);
grGroupMembers.query();
while (grGroupMembers.next()) {
userArray.push(grGroupMembers.user.toString()); // Add the user sys_id to the array
}
return userArray;
}
// Get users in both groups
var group1Users = getUsersInGroup(group1SysId);
var group2Users = getUsersInGroup(group2SysId);
// Function to remove all users from a group
function removeUsersFromGroup(groupSysId) {
var grGroupMembers = new GlideRecord('sys_user_grmember');
grGroupMembers.addQuery('group', groupSysId);
grGroupMembers.query();
while (grGroupMembers.next()) {
grGroupMembers.deleteRecord(); // Remove user from the group
}
}
// Function to add users to a group
function addUsersToGroup(usersArray, groupSysId) {
for (var i = 0; i < usersArray.length; i++) {
var grGroupMember = new GlideRecord('sys_user_grmember');
grGroupMember.initialize();
grGroupMember.user = usersArray[i];
grGroupMember.group = groupSysId;
grGroupMember.insert(); // Add user to the group
}
}
// Remove all users from both groups before swapping
removeUsersFromGroup(group1SysId);
removeUsersFromGroup(group2SysId);
// Add Group 1 users to Group 2
addUsersToGroup(group1Users, group2SysId);
// Add Group 2 users to Group 1
addUsersToGroup(group2Users, group1SysId);
gs.log('User swap between groups completed.');
Please mark my response helpful and accepted solution if it addresses your question.