Need a script to copy roles and groups from one user to another user
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-12-2023 05:15 AM
Hi All,
Need a script to copy roles and groups from one user to another user
For example
I will give the user name like below
Copy From : sallis@gmail.com
Copy To : rizwan@gmail.com
1 REPLY 1
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-12-2023 05:46 AM - edited 10-12-2023 05:49 AM
Hi @Saib1 ,
Can you try with the below code.
(function() {
var copyFromUser = 'sallis@gmail.com'; // Replace with the 'Copy From' user's username
var copyToUser = 'rizwan@gmail.com'; // Replace with the 'Copy To' user's username
// Find the 'Copy From' user record
var copyFromUserRecord = new GlideRecord('sys_user');
if (copyFromUserRecord.get('user_name', copyFromUser)) {
// Find roles assigned to the 'Copy From' user
var roles = new GlideRecord('sys_user_has_role');
roles.addQuery('user', copyFromUserRecord.sys_id);
roles.query();
while (roles.next()) {
// Assign roles to the 'Copy To' user
var role = new GlideRecord('sys_user_has_role');
role.initialize();
role.user = getCopyToUserId(copyToUser); // Function to get 'Copy To' user's sys_id
role.role = roles.role.toString();
role.insert();
}
// Find groups assigned to the 'Copy From' user
var groups = new GlideRecord('sys_user_grmember');
groups.addQuery('user', copyFromUserRecord.sys_id);
groups.query();
while (groups.next()) {
// Assign groups to the 'Copy To' user
var group = new GlideRecord('sys_user_grmember');
group.initialize();
group.user = getCopyToUserId(copyToUser); // Function to get 'Copy To' user's sys_id
group.group = groups.group.toString();
group.insert();
}
gs.print('Roles and groups copied successfully.');
} else {
gs.print('User not found: ' + copyFromUser);
}
function getCopyToUserId(username) {
var user = new GlideRecord('sys_user');
if (user.get('user_name', username)) {
return user.sys_id.toString();
}
return '';
}
})();
Mark my answer helpful & accepted if it helps you resolve your query.
Thanks,
Danish