Flow Designer Increment a string field that ends with a number by 1

yoli1
Tera Contributor

hello team we have a form automation that creates a new server. the requirements is to check to see if the server requested has already been created in our CMDB and if it already exist then check for the next available number

name of server : MAVNBTMT01

If a server already exist like the one above, then  increment the last numbers of the name.  So the next would be MAVNBTMT02 or MAVNBTMT03

this is my code :

(function execute(inputs, outputs) {
    var baseName = inputs.locCode + inputs.operatingSystem + inputs.formFactor;
    var gr = new GlideRecord('cmdb_ci_server'); // Replace with your actual table name

    // Query the existing servers that match the base name
    gr.addQuery('name', 'STARTSWITH', baseName);
    gr.query();

    // Initialize the next server number
    var nextServerNumber = 1;

    // Find the highest existing number and increment it
    while (gr.next()) {
        var currentServerName = gr.name.toString();
        var numberPart = currentServerName.replace(baseName, '');
        var currentNumber = parseInt(numberPart, 10);

        if (!isNaN(currentNumber) && currentNumber >= nextServerNumber) {
            nextServerNumber = currentNumber + 1;
        }
    }

    var incrementedBaseName = baseName + nextServerNumber.toString().padStart(2, '0');

    outputs.newservername = incrementedBaseName;
})(inputs, outputs);

in the output if the name is MAVNBTMT01 i get MAVNBTMTundefined 

2 REPLIES 2

Anand Kumar P
Giga Patron
Giga Patron

Hi @yoli1 ,

 

Use  var nextServerNumber = 0;  not 1.

 

Thanks,

Anand

SHARANsnow7
Tera Guru

HII @yoli1 

SHARANsnow7_0-1696922385509.png