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.

Code is not working

Prithvi Ramesh1
Mega Sage

Requirement:

There is an expiry date field in the CMDB table. Email notifications need to be triggered at specific intervals—10 days, 5 days, 1 day before, and on the exact expiry date and time.

 

Scheduled Job Script:

 

(function() {
    var grUser = new GlideRecord('cmdb_ci');
    grUser.addNotNullQuery('u_expiry_date');
    grUser.query();
    var today = grUser.u_expiry_date.getDisplayValue(); // current date and time
    var expiryDays = [10, 5, 1, 0]; // Days before expiry to trigger
    for (var i = 0; i < expiryDays.length; i++) {
        today.addDaysUTC(-expiryDays[i]); // Calculate target expiry date
        while (grUser.next()) {
            gs.eventQueue('u_infrastructure_accounts.u_password_last_rotation_date', grUser,'', '',today);
        }
    }
})();
1 REPLY 1

YaswanthKurre
Tera Guru

Hi @Prithvi Ramesh1 ,

 

Give this a try:

(function() {
    var expiryDays = [10, 5, 1, 0]; // Days before expiry to trigger
    var now = new GlideDateTime();

    var grCI = new GlideRecord('cmdb_ci');
    grCI.addNotNullQuery('u_expiry_date');
    grCI.query();

    while (grCI.next()) {
        var expiryDate = grCI.getValue('u_expiry_date'); // Get expiry date as GlideDateTime
        var expiryGDT = new GlideDateTime(expiryDate);

        for (var i = 0; i < expiryDays.length; i++) {
            var targetDate = new GlideDateTime(expiryGDT);
            targetDate.subtractDaysUTC(expiryDays[i]);

            // Compare only the date part
            if (targetDate.getDate() == now.getDate()) {
                gs.eventQueue('u_cmdb_expiry_notification', grCI, '', '');
                break; // Avoid sending multiple events for the same record
            }
        }
    }
})();

 

Please mark this as helpful and correct, if this helps you.

 

Thanks,

Yaswanth