Re-numbering duplicate KB article numbers while considering versioning
You may or may not be aware that the number field for records across the platform is not unique by default. Usually this presents no issue, however when importing records it can cause duplicate numbers to be used.
If you only have a handful, manually renumbering works fine. But what if you have 1000+?
Unfortunately ServiceNow doesn't have a shareable solution for this and I was directed to the community for help with a script. There are a few posts about renumbering duplicate records, but nothing specific to knowledge and certainly none that account for versioning (multiple versions of an article share the same number). I used a great post from Allen A to get me started and built off of that to account for the versioning. You can find the original post here.
I was able to develop a working solution and thought I'd share the code in case anyone has the same issue in the future! This would be run as a background script.
getDupes();
function getDupes() {
var dupNum = [];
var ga = new GlideAggregate('kb_knowledge');
ga.addAggregate('COUNT', 'number');
ga.addQuery('number', '!=', '');
ga.groupBy('number');
ga.addHaving('COUNT', '>', 1);
ga.addQuery('workflow_state', 'published'); //comment this out if you have duplicates in draft
ga.query();
while (ga.next()) {
dupNum.push(ga.number.toString());
}
gs.print('The KB table has ' + ga.getRowCount() + ' duplicates based on number field...');
//Loop through duplicate array
for (i=0;i<dupNum.length;i++) {
var gr = new GlideRecord("kb_knowledge");
gr.addQuery("number",dupNum[i]);
gr.query();
while(gr.next()) {
////versions share number and article ID. In the event of duplicate numbers, article ID can be used to identify versions that should retain the same number as its predecessors
var versions = new GlideRecord ('kb_knowledge');
versions.addQuery('article_id', gr.article_id);
versions.addEncodedQuery("article_id!=NULL");
versions.query();
var nm = new NumberManager('kb_knowledge');
var newNum = nm.getNextObjNumberPadded();
while(versions.next()){
versions.number = newNum;
versions.update();
}
}
}
}
https://www.servicenow.com/community/now-platform-articles/re-numbering-duplicate-kb-article-numbers-while-considering/ta-p/2309720