Please use docs.servicenow.com for the latest documentation.

This site is for reference purposes only and may not be accurate for the latest ServiceNow version

Useful User Scripts

From Wiki Archive
Jump to: navigation, search
Note
Note: This article applies to Fuji. For more current information, see Useful Scripts at http://docs.servicenow.com

The ServiceNow Wiki is no longer being updated. Please refer to http://docs.servicenow.com for the latest product documentation.


This is a searchable version of the Useful User Admin Scripts. For an easy-to-navigate version, visit the Useful Scripts portal.



Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Add Role to Every User

Type: Client Script, Background Script

Table: sys_user

Description: Adds a role to every user. In this sample, the role being added is Self Service. To add a different role, simply substitute the desired role for self_service.

Parameters:

Script: <source lang="javascript"> var gr = new GlideRecord("sys_user"); gr.query(); while(gr.next()) {

 if (gr.accumulated_roles.toString().indexOf(",self_service,") == -1) {
  gr.roles = gr.roles + ",self_service";
  gr.update();
}

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Change a User's References to Another User

Type:

Table: sys_user

Description: This script changes all sys_user references in an instance from one user to another. Replace name1 and name2 with unique user_names – modify to use sys_ids if user_names aren’t unique.

Warning: this may cause performance issues on large instances time. Also: this is irreversible, so be sure to use only when necessary.

Parameters:

Script: <source lang="javascript"> doit('name1','name2');

function doit(username1,username2) {

 var usr1 = new GlideRecord('sys_user');
 var usr2 = new GlideRecord('sys_user');
 var num = 0;

 if (usr1.get('user_name',username1) && usr2.get('user_name',username2)) {
   var ref;
   var dict = new GlideRecord('sys_dictionary');
   dict.addQuery('reference','sys_user');
   dict.addQuery('internal_type','reference');
   dict.addQuery('sys_class_name','!=','wf_activity_variable');
   dict.query();
   while (dict.next()) {
     num = 0;
     ref = new GlideRecord(dict.name.toString());
     ref.addQuery(dict.element,usr1.sys_id);
     ref.query();
     while (ref.nextRecord()) {
       ref.setValue(dict.element.toString(),usr2.sys_id); 
       ref.setWorkflow(false);
       ref.update();
       num++;
     }
     if (num > 0) {
       gs.print(dict.element + ' changed from ' + usr1.user_name + 
         ' to ' + usr2.user_name + ' in ' + num + ' ' + dict.name + ' records');
     }
   }
 }

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Force Password Reset 90 Days After Last Change

Type: Installation Exit, Event, Client Script, Scheduled Script

Table:

Description: Unlike the Force Password Reset Every Ninety Days method, this series of policies will force a user to reset their password ninety days after the last change. Because it is more context-sensitive, it requires four changes:

  1. Modifying the ValidatePassword Installation Exit.
  2. Register an event for password changes.
  3. Create a script to respond to password changes.
  4. Create a daily script to check when the last password change has been effected.

Notice that this method requires creating a field u_password_last_reset on the sys_user table.

Parameters:

Script:


Note
Note: These API calls changed in the Calgary release:
  • GlideEventManager replaces Packages.com.glide.policy.EventManager
  • GlideDateTime replaces Packages.com.glide.glideobject.GlideDateTime

The new script object calls apply to the Calgary release and beyond. For releases prior to Calgary, substitute the packages calls as described above. Packages calls are not valid beginning with the Calgary release. For more information, see Scripting API Changes.


Step One Navigate to System Definition > Installation Exits, and open the ValidatePassword record. Replace with the following <source lang="javascript">process:function() {

  GlideEventManager.queue("sys_user.password.changed", "", gs.getUserID(), gs.getUserName());
  return true;

} </source> Mark the Installation Exit as Active. Save.

Step Two Register your Event by navigating to System Policy > Registry. Create a new record with the following values:

Name: sys_user.password.changed
Table: User [sys_user]
Description: Indicates user password has changed
Fired by: ValidatePassword Installation Exit

Step Three Create a new script action by navigating to System Policy > Script Actions. Create a record with the following values:

Name: SNC User Password Changed
Event name: sys_user.password.changed
Active: checked

Use the following script: <source lang="javascript">// // When the user password changes then set the u_password_last_reset field // to now so we know when to force another update // var gr = new GlideRecord("sys_user"); if (gr.get(event.parm1.toString())) {

 // Do something based on the Password Changing
 gs.log("The user password changed so do something else...");
 gr.u_password_last_reset = gs.now();
 gr.update();

} </source>

Step Four Create a daily scheduled job with the following code: <source lang="javascript">gs.print("Checking passwords for 90 day reset limit"); var gr = new GlideRecord('sys_user'); gr.query(); while (gr.next()) {

  var resetDate = new GlideDateTime();
  resetDate.setDisplayValue(gr.u_password_last_reset.getDisplayValue());
  var todaysDate = new GlideDateTime();
  todaysDate.setDisplayValue(gs.now());
  var resetNum = resetDate.getNumericValue();
  var todaysNum = todaysDate.getNumericValue();
  var passwordAge = todaysNum - resetNum;
  // NOTE 7776000000 is 90 days
  if (passwordAge >= 7776000000) {
     gr.password_needs_reset = true;
     gr.update();
  }

}</source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Force Password Reset Every Ninety Days for Every User

Type: Scheduled Script

Table:

Description: Scheduled job running every 90 days will force a passwords reset for every user. Please note that this scheduled job forces a password change for every user, regardless of how recently they changed their password. For a more sophisticated method, see Force Password Reset 90 Days After Last Change.

Parameters:

Script: Scheduled Script: <source lang="javascript">gs.print("Resetting all users to change password...");

var gr = new GlideRecord('sys_user'); gr.query(); while (gr.next()) {

     gr.password_needs_reset = true;
     gr.update();
 }    

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Get Company sys id from Logged-in User

Type:

Table:

Description: Get a Company's sys_id from Logged-in User.

Note: if in a condition widget or default value for a field, use javascript:gs.getUser().getCompanyID()

Parameters:

Script: <source lang="javascript">gs.getUser().getCompanyID() </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Get User's Region

Type: Business Rule

Table:

Description: This is a business rule that defines a function getUserRegion to check for the region of the user. Once the business rule is defined, it is possible to reference the user's region dynamically (e.g. to filter based on user's region).

Parameters:

Script: <source lang="javascript">function getUserRegion() {

 var u = gs.getUserID();
 var gr = new GlideRecord('sys_user');
 gr.addQuery('sys_id',u);
 gr.query();
 while (gr.next()) {
   var answer = gr.u_region; //you will need to replace u_region with the actual field name on your user record
   return answer;
 }

}</source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Reset Passwords for All Users to Set String

Type:

Table:

Description: Resets password for every single user, overwriting their existant password. Use with caution. Replace abc123 with the string in question.

Parameters:

Script: <source lang="javascript">var gr = new GlideRecord("sys_user"); gr.query(); while(gr.next()) {

 gr.user_password.setDisplayValue("abc123");
 gs.log("updating password for " + gr.user_name);
 gr.update();

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Restrict Access to Admin Role

Type: Business rule

Table: User Role [sys_user_has_role]

Description: Allows only users with the admin role to grant or remove the admin role. Prevents users who do not have the admin role from granting or removing the admin role.

Parameters: When: Before (insert,update,delete), Condition: !gs.hasRole('admin')

Script: <source lang="javascript">if (current.role.getDisplayValue()=='admin') {

     gs.addErrorMessage('only admins can add/remove the admin role')
     current.setAbortAction(true);

} </source>

Note
Note: This article applies to Fuji. For more current information, see Restrict View by Role at http://docs.servicenow.com

The ServiceNow Wiki is no longer being updated. Please refer to http://docs.servicenow.com for the latest product documentation.


Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Restrict Form Views by Role

Type: Business Rule

Table: global

Description: Generally the view used on a form is controlled by either specifying the sysparm_view parameter in the url or module properties, or by inheriting the view from the previous form or list. In some cases this does not apply, such as opening a referenced field form from a record producer. In this case you may want to control the view of the form based on roles. Here's an example of controlling the view of the user form.

This script is based off of the out-of-box global business rule incident functions.

Parameters:

Script: <source lang="javascript"> //Force non-itil users to the ess view for sys_user

//To use on other tables, replace sys_user with the table name

//Business rule: User View Filter //Table:global //Runat:server

function sys_userGetViewName() { if (gs.hasRole("itil")) {return; } if (view.startsWith("ess")) {return;} // do not change view if it starts with sys_ (e.g. sys_ref_list) if (view.startsWith("sys_")) {return;} answer = "ess"; }

function sys_user_listGetViewName() { sys_userGetViewName(); } </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Restrict Record Update to Admin or IT Contact

Type: Client Script

Table:

Description: Prevents any user other than an Admin or a designated IT Contact from updating a form. The IT Contact only applies if there is an IT Contact reference field being used.

Parameters:

Script: <source lang="javascript">function onSubmit() {

var isAdmin = g_user.hasRole('admin');
var cuser = g_form.getReference('it_contact').user_name; 
if ((isAdmin) || (cuser == g_user.userName)){
  return true;
} else {
  alert("You are not an admin, nor are you the IT contact for this application. You therefore cannot make any modifications");
  return false;
}

}</source>