Jun 29, 2023

Create Text file and send to MID Server in ServiceNow

ServiceNow Export Set offers to export data in a limited format, as shown below. This article will discuss how to create a .txt file and export it to MID Server.

To create a text file and send it to a MID Server in ServiceNow, you can combine the file creation and MID Server file transfer steps

Create a text file and attach to the MID Server Attachments (ecc_agent_attachment) record.

Below is the Script Include to create the .txt file and transfer to the MID Server. The Script Include have some functions.
/* esline no-undef:error,no-unused-vars:warning */
var FileTransferUtil = Class.create();
FileTransferUtil.prototype = {
    initialize: function() {},
    CreateTextFilefunction() {
        var fileContent = "This is a sample text file";
        fileName = 'CustomeText.txt';

        var eccAttachment = new GlideRecord('ecc_agent_attachment');
        eccAttachment.initialize();
        eccAttachment.name = 'Export Set Attachment';
        eccAttachment.short_description = 'Exporting Custom Text File:' + fileName;
        var eccAtt_sys_id = eccAttachment.insert();

        var attachment = new GlideSysAttachment();
        var attachmentRec = attachment.write(eccAttachment, fileName, "text", fileContent);
        if (!gs.nil(attachmentRec)) {
            var xmlString = '<?xml version="1.0" encoding="UTF-8"?>' +
                '<parameters>' +
                '<parameter name=\"stream_relay_response_topic\" value=\"ExportSetResult\"/>' +
                '<stream_relay_source attachment_sys_id=\"' + attachmentRec + '\" type=\"AttachmentSource\"/>' +
                '<stream_relay_transform attachment.table_sys_id=\"' + eccAtt_sys_id + '\" order=\"0\" stream_relay_transfer_progress_interval=\"150\" type=\"AttachmentProgressTransformer\"/>' +
                '<stream_relay_sink path="\/' + fileName + '\" type=\"FileSink\"/>' +
                '</parameters>';
            //stream_relay_sink path update as per requirement
            // agent/export/ is base folder
            // Create ECC Record
            var eccQueue = new GlideRecord('ecc_queue');
            eccQueue.initialize();
            eccQueue.agent = 'mid.server.XXXXXXXXX';//MID Server Name
            eccQueue.topic = 'StreamPipeline';
            eccQueue.queue = 'output';
            eccQueue.state = 'ready';
            eccQueue.payload = xmlString;
            eccQueue.insert();
        }
    },
    type: 'FileTransferUtil'
};
Below is how to consume the Script Include

var util=new FileTransferUtil();
util.CreateTextFile();