query userID values where UserID contains "x" in position 3

Bcrant
Tera Contributor

hello, all.

 

I've received a request to query all active users in our instance where the userID (user_name) contains a 9 in the 3rd position. I'm struggling with this background script to get a count and hoping someone may be able to assist. An example value would be "AZ98754". Can anyone assist with an example?

1 ACCEPTED SOLUTION

Vishal Birajdar
Giga Sage

Hi @Bcrant 

 

you can add query like 

gr.addQuery('user_name', 'LIKE', '__9%');

 

Can you try below code...!!

 

var grUser= new GlideRecord('sys_user');
grUser.addActiveQuery();
grUser.addQuery('user_name', 'LIKE', '__9%');
grUser.query();
while (grUser.next()) {
    gs.info("user:"+ grUser.user_name);
}

 

 

Hope this works

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

View solution in original post

4 REPLIES 4

Vishal Birajdar
Giga Sage

Hi @Bcrant 

 

you can add query like 

gr.addQuery('user_name', 'LIKE', '__9%');

 

Can you try below code...!!

 

var grUser= new GlideRecord('sys_user');
grUser.addActiveQuery();
grUser.addQuery('user_name', 'LIKE', '__9%');
grUser.query();
while (grUser.next()) {
    gs.info("user:"+ grUser.user_name);
}

 

 

Hope this works

 

Vishal Birajdar
ServiceNow Developer

I know one thing, and that is that I know nothing.
- Socrates

Danish Bhairag1
Tera Contributor

Hi @Bcrant ,

 

Can you try the below code

// Initialize the GlideRecord object for the 'sys_user' table
var userGR = new GlideRecord('sys_user');

// Define the query to find active users where userID contains '9' in the 3rd position
userGR.addActiveQuery(); // This ensures you're only considering active users
userGR.addQuery('user_name', 'LIKE', '__9%'); // '__' represents any two characters before '9'

// Execute the query to find matching records
userGR.query();

// Count the number of records
var userCount = userGR.getRowCount();
while(userGR.next()){
//execute your logic here
}
// Print the count of active users with '9' in the 3rd position of their userID
gs.info('Number of active users with "9" in the 3rd position of userID: ' + userCount);

 

Mark my answer helpful & accepted if it helps you resolve your query.

 

Thanks,

Danish

Thank you @Danish Bhairag1 your query is very helpful.

Bcrant
Tera Contributor

Thank you @Vishal Birajdar for your quick response. Query worked great.