Best way to update multiple asset records

JohnMMcLaughlin
Tera Contributor

Service Now Gurus,

I have the following issue:   We have recently added our hardware assets to SN, and we have assigned them to users, however we have noticed the Location field isn't being updated and long story short, we weren't pulling across our users location via our LDAP import, this has now been fixed and each of our user records is now showing a location.

For most of our assets, there is an assigned user but an empty location field, if I manually remove the assigned to user and save the record then add in the original assigned to user the location field updates, but I don't want to do that for all our assets, I have put together the following script that looks to work in our Dev environment but I'm cautious about running in our Prod environment before others give it the ok (first script within SN) or in case there is better way to achieve what I am trying to.

Script below:

var asset = new GlideRecord('alm_asset');

asset.addNullQuery('location');

asset.addNotNullQuery('assigned_to');

asset.query();

while (asset.next())

{

var assigned = asset.getDisplayValue('assigned_to');

var user = new GlideRecord('sys_user');

user.addQuery('name',assigned);

user.query();

while (user.next())

{

var sysId = user.getUniqueValue();

var u_user = gs.getUser().getUserByID(sysId);

var u_location = u_user.getLocation();

}

gs.log("Location: " + u_location);

asset.setValue('location', u_location);

asset.update();

}

So the thinking is I select all records that are assigned but don't have a location, I then find the assigned to user for the asset and then find their user sys_id, from there I query the user table to get the users location and then I set the location field in the asset record to match that of the user and then update the record.

Please pick apart the code and let me know if there is a better way to do this.

Thanks in advance,

John.

1 ACCEPTED SOLUTION

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hello John,



Below is the modified script. This will fetch assigned_to user location and update those records with empty location.


var asset = new GlideRecord('alm_asset');  


asset.addNullQuery('location');  


asset.addNotNullQuery('assigned_to');  


asset.query();  


while (asset.next())  


{  


asset.location = asset.assigned_to.location;  


asset.setWorkflow(false); //To turn off the notification or business rule on the alm_asset table.


asset.update();  


}




View solution in original post

10 REPLIES 10

yes you are right. i did not think about that