We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

How to assign a survey only to a specific group using SNC.AssessmentCreation()

Pushpanjali3
Tera Contributor

I’m trying to assign a survey to a specific user group using a server-side script in ServiceNow, but I’m running into issues. Here’s what I’m doing:

What I want:

  • Only users in the group “GBS Pillar survey” should be assigned the survey

    Scheduled Job:

var surveyId = 'ba6664732b43fa10e31df4f9dd91bfb3'; // My survey sys_id
var returnIds = new SNC.AssessmentCreation().createAssessments(surveyId);
var returnValues = returnIds.split(',');
var users = (returnValues.length >= 2) ? parseInt(returnValues[1]) : 0;

if (users > 0)
gs.log(gs.getMessage('Invited {0} users to take the survey.', users+''));
else
gs.log(gs.getMessage('No new invitation sent for the survey'));

1 REPLY 1

pavani_paluri
Tera Guru

Hi @Pushpanjali3 

 

Right now, your script is inviting everyone who qualifies for the survey. That’s because the function you’re using (createAssessments) doesn’t know anything about groups — it just sends out invitations broadly.

If you only want people in the GBS Pillar survey group to get the survey, you need to do two things:

1. Find the group
Look up the group record in ServiceNow by its name (“GBS Pillar survey”).

2. Get the users in that group
ServiceNow keeps track of group membership in a table called `sys_user_grmember`. You query that table to get all the users who belong to your group.

3. Send the survey to those users only
Instead of the bulk method (`createAssessments`), you loop through each user and call the single-user method (`createAssessment`) with the survey ID and the user’s ID. That way, only those specific people get invited.

4. Log the results
Count how many users you successfully invited, and log a message like “Invited 12 users to take the survey.

 

var surveyId = 'ba6664732b43fa10e31df4f9dd91bfb3'; // Survey sys_id
var groupName = 'GBS Pillar survey';

// Find the group
var groupGR = new GlideRecord('sys_user_group');
groupGR.addQuery('name', groupName);
groupGR.query();

if (groupGR.next()) {
var groupSysId = groupGR.sys_id.toString();

// Get users in that group
var userGR = new GlideRecord('sys_user');
userGR.addQuery('sys_id', 'IN',
new GlideAggregate('sys_user_grmember')
.addQuery('group', groupSysId)
.getAggregate('user')
);
userGR.query();

var invitedCount = 0;
while (userGR.next()) {
// Create assessment for each user
var assessmentId = new SNC.AssessmentCreation()
.createAssessment(surveyId, userGR.sys_id.toString());
if (assessmentId) {
invitedCount++;
}
}

if (invitedCount > 0)
gs.log('Invited ' + invitedCount + ' users to take the survey.');
else
gs.log('No new invitation sent for the survey');
} else {
gs.log('Group "' + groupName + '" not found.');
}

 

Please mark this response as help if this solves your problem.

Thanks,

Pavani Paluri