Garrick
ServiceNow Employee
ServiceNow Employee

So a colleague was asking if we had a login count on the user records. A quick poke in the wiki and our instance seemed to not show one out of the boxcloud, but it seemed simple enough task to accomplish with Script Actions.

Script Actions are a way of triggering a server side script based on a standard event in the system. A great example of this is at login. When a user logs in, the Event Log creates a record with the user_id and IP address of the person logging in. We also have a few standard script actions that do things like take the login time and write it to the user record as "last login time". Often we're quick to jump down the path of complex business rules, weird client scripts or other trickery to accomplish what might otherwise be quite easier in leveraging the script actions.

Based on this, we thought, why not? Let's create a field on the user record (sys_user) that's called "Login Count" (this became "u_login_count"). We'll have it just be a simple integer field that keeps track of how many times a user logs in. We don't need to put a lot of complexity behind it, but might want to also include a quick ACL for making it read-only. After that, we headed over to Script Actions from the System Policy menu and create a new Script Action (find out more about Script Actions here in the wiki!).

We decided to call ours Login Counter and the Event Name is "login". Seems pretty good so far, but now what? Well now, we need to include some code to tell that field to update each time someone logs in. It might look something like this:



//
// Set the login count
//
var gr = new GlideRecord("sys_user");
gr.addQuery("user_name", event.parm1);
gr.query();
if (gr.next()) {
gr.u_login_count += 1;
gr.update();
}


or

Login Counter and I like putting messages in alt tags

After checking the syntax to clean up the typos we knew we'd make, it was good to go. A few quick tests and all seems to be checking out. Keep in mind if you're an admin and doing some impersonations (I don't mean Elvis), it will count as a login. If you really cared about this, there are a few ways to correct; however, if you get it so far, I'm sure they'll be easy enough to figure out.

Hope this helps a few of you! Have a great weekend!

Garrick

1 Comment