By using fix script we need add roles to the groups .

aarya1
Giga Contributor

Hi

My requirement is to add  one role to particular groups by using fix script.

There are some filter conditions while querying the group table , below are the filter conditions 

Group should be active, group should be itil, and group should be non working group.

By using those conditions we need to get that particular groups if those conditions are matched then we need to check that particular groups has sn_role , if this role is there to that groups then dont do any thing , if that role is not there to that groups then add sn_role.

This is my requirement.

Please suggest with your answers.

Thanks in advance

Regards

Aarya 

1 ACCEPTED SOLUTION

Hi,

something like this; enhance it

addRole();

function addRole(){
	try{
		var gr = new GlideRecord("sys_user_group");
		gr.addEncodedQuery("Your Query"); // give your query here
		gr.query();
		while(gr.next()) {

			var gr1 = new GlideRecord("sys_group_has_role");
			gr1.addQuery("group", gr.getUniqueValue());
			gr1.addQuery("role.name", "sn_role"); // give exact role name here
			gr1.query();
			if (!gr1.hasNext()) {
				gr1.initialize();
				gr1.group = gr.getUniqueValue();
				gr1.setDisplayValue('role','sn_role'); // give exact role name here
				gr1.insert();
			}
		}
	}
	catch(ex){
		gs.info(ex);
	}
}

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

16 REPLIES 16

Please start from your side and it would be learning for you as well

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Hi @Ankur Bawiskar, I ran the script below and it added the Role to every group, not just the groups where u_company is ABC.  Will you please help me get this script to only add the role to groups where the value of the u_company field on the sys_user_groups table is 'ABC'?

 

addRole();

function addRole(){
	try{
		var gr = new GlideRecord("sys_user_group");
		gr.addEncodedQuery('group.u_company=ABC'); // give your query here
		gr.query();
		while(gr.next()) {

			var gr1 = new GlideRecord("sys_group_has_role");
			gr1.addQuery("group", gr.getUniqueValue());
			gr1.addQuery("role.name", "JR Test Role for ABC groups"); // give exact role name here
			gr1.query();
			if (!gr1.hasNext()) {
				gr1.initialize();
				gr1.group = gr.getUniqueValue();
				gr1.setDisplayValue('role','JR Test Role for ABC groups'); // give exact role name here
				gr1.insert();
			}
		}
	}
	catch(ex){
		gs.info(ex);
	}
}