Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Background script to close Requests when RITM is Closed complete

AdrianHolm
Tera Guru

Hello Community,

As the title says; I could need some help writing a background script to close all our Requests when RITM have State Closed complete. We have approximately 130 Requests where RITM is Closed complete, so I believe there is a issue with a BR in our instance. I'm currently on the path of learning to write my own scripts, but unfortunately this is out of my skills. 

Thanks in advance!

 

Best regards,
Adrian H

14 REPLIES 14

I would absolutely check this out - thank you a lot Mark! 

I'll mark the correct answer when it's been replied. 

AbhishekGardade
Giga Sage

Check out this:

var ritm = new GlideRecord('sc_req_item');

ritm.addQuery('state', '3'); // here value for Closed complete is 3, you can check what value you have

ritm.query();

while(ritm.next()){

gs.log("RITM Number: "+ritm.number);

// here you can use what you want to set for state or you can use ritm.setValue('state','value for closed') instead using below.

ritm.setDisplayValue('state','Closed');

ritm.active = false;

ritm.setWorkflow(false);

ritm.update();

}

Please mark as Correct Answer and Helpful, if applicable.
Thanks!
Abhishek Gardade
Hexaware Technologies

Thank you,
Abhishek Gardade

VigneshMC
Mega Sage

Try this

var req = new GlideRecord('sc_request');
req.addActiveQuery();
req.query();
while(req.next()){
	// check if there are any active requested items under it
	var req_item = new GlideRecord('sc_req_item');
	    req_item.addQuery('request',req.sys_id);
	    req_item.addActiveQuery();
	    req_item.setLimit(1);
	if(req_item.next()){
		// do nothing
	}
	else{
		req.state = '3';
		req.active = false;
		req.setWorkflow(false);
		req.update();
	}
	
}

This is correct approach, this will work.

Just instead of if/else id use

if(!req_item.hasNext()){
req.state = '3';
req.active = false;
req.setWorkflow(false);
req.update();
}

-Anurag

Thanks all, I really appreciate all the answers!

However, we still have some Active Requests - so when I tried the script above it seems to be closing the active ones too. Just like @Mark Roethof stated, I'd probably avoind setWorkflow(false)? Any suggestions?