How to update user records through backend script

kapil_shinde
Tera Expert

Hi All,

 

Need assistance on writing a backend script to update user records (a custom field) based on another custom field for 1000 records. Kindly suggest how to achieve this requirement.

 

Thanks

 

Kapil

6 REPLIES 6

RaghavSh
Kilo Patron

You can run a fix or background script:

 

var user = new GlideRecord("sys_user");
user.addEncodedQuery(" "); // pass your encoded query which will fetch 1000 records
user.query();
while(user.next())
{
user.field_name=""; // pass the field name and the bvalue to set
user.update();
}

 

 

Encoded query can be built using the funnel icon at top of the list view of the table.

Note: All scripts should be tested in testing env before executing in prod.


Raghav
MVP 2023

Danish Bhairag2
Tera Sage
Tera Sage

Hi @kapil_shinde ,

 

Try below code.

 

(function() {

    var userGr = new GlideRecord('sys_user');
    userGr.addEncodedQuery('add your query for 1000 records');
    userGr.addQuery('YOUR_CONDITION_FIELD', 'YOUR_CONDITION_VALUE'); // Add your conditions here
    userGr.query();
    while (userGr.next()) {
        userGr.custom_field_2 = 'NEW_VALUE'; // Set the new value for the custom field
        userGr.update();
    }
    gs.info('Updated ' + userGr.getRowCount() + ' user records.');

})();

 

Thanks,

Danish

 

Thanks Danish,

'New_Value' is different for different 'Your_Condition_Value' so i need to pass 'New_Value' and 'Your_Condition_Value' 1000 times may be in a batch of 100. kindly suggest.

Hi @kapil_shinde ,

 

If u can provide a snip of the records which we are talking abt that would be helpful. Also yes you can execute the script in a batch  for whom the the 'New Value' and 'Your Condition value' are same.

 

Thanks,

Danish