Last active
July 21, 2023 18:29
-
-
Save thisnameissoclever/8f435fb2009695cf34d7dfe4cc0564d2 to your computer and use it in GitHub Desktop.
Calculate the MD5 hash of an attachment in ServiceNow (Scope & global)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var recordTable = 'incident'; | |
var idOfRecord = '755d52b137b0b30090b68cf6c3990e6f'; | |
var grAttachment = getAttachmentRecord(recordTable, idOfRecord, 'example text doc.txt', true); | |
if (grAttachment !== false) { | |
var attachmentStream = new GlideSysAttachment().getContentStream( | |
grAttachment.getValue('sys_id') | |
); | |
var gDigest = new GlideDigest(); | |
var base64MD5 = gDigest.getMD5Base64FromInputStream(attachmentStream); //Scope only | |
gs.info(base64MD5); | |
} | |
/** | |
* Get the GlideRecord object for an attachment on a given record. | |
* @param {string} recordTable - The table name for the record that has the attachment. Example: "incident". | |
* @param {string} idOfRecord - The sys_id of the record that has the attachment. | |
* @param {string} [nameOfFile] - The name of the attachment file to retrieve. | |
* @param {boolean} [exactMatch] - Whether to look for an exact match on the file-name provided. If false (or unspecified), a "starts with..." query will be done. | |
* This param only applies if a valid file name is provided. | |
* @returns {GlideRecord|boolean} - The GlideRecord for the related sys_attachment record. | |
*/ | |
function getAttachmentRecord(recordTable, idOfRecord, nameOfFile, exactMatch) { | |
var grAttachment = new GlideRecord('sys_attachment'); | |
grAttachment.addQuery('table_name', recordTable); | |
grAttachment.addQuery('table_sys_id', idOfRecord); | |
if (nameOfFile && exactMatch) { | |
//If the file name is provided, and exactMatch is true | |
grAttachment.addQuery('file_name', nameOfFile); | |
} else if (nameOfFile) { | |
//If the file name is provided, but exactMatch is not, or is false | |
grAttachment.addQuery('file_name', 'STARTSWITH', nameOfFile); | |
} | |
//If multiple attachments match, get newest one | |
grAttachment.orderByDesc('sys_created_on'); | |
grAttachment.setLimit(1); //Be more efficient | |
grAttachment.query(); | |
if (grAttachment.next()) { | |
return grAttachment; | |
} | |
gs.debug('Attachment for record on table ' + | |
recordTable + ' with sys_id ' + idOfRecord + | |
' not found with the specified arguments.'); | |
return false; //If attachment is not found, return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment