Solved: Change file name in Mid Server - ServiceNow Community

Change file name in Mid Server

Frank Silveira1
Kilo Expert

Hello Experts,

I currently have a requirement from a customer where I need to replace the name of a file in the Mid Server after a scheduled export.

The idea here is that the file goes with the name in the format "file_name_datetime" and the customer needs "datetime_file_name" for the file to be correctly read by another system.

My main idea was to rename the file after the export to the correct format, but if there is a way of changing the file name to the required one I could do that also.

 

I would love to hear from you guys as I have no idea how can I do this.

 

Thanks in advance.

1 ACCEPTED SOLUTION

Frank Silveira1
Kilo Expert

Hello All,

 

Thank you for your answers. This is how I finally achieved the desired result:

 

Script include:

 

initialize: function() {
        this.filePath = gs.getProperty('directory_path');
        this.midServer = gs.getProperty('midserver');
        this.authMidServerBase64 = gs.getProperty('authmidserver');
    },

    nameChange: function(exportSetName) {

        var exportGr = new GlideRecord("sys_export_set_run");
        exportGr.addEncodedQuery("set.nameSTARTSWITH" + exportSetName);
        exportGr.orderByDesc("completed");
        exportGr.query();

        if (exportGr.next()) {

            var attachSysID = exportGr.ecc_agent_attachment.sys_id;

        }

        var attachGr = new GlideRecord("sys_attachment");
        attachGr.addEncodedQuery("table_sys_idSTARTSWITH" + attachSysID);
        attachGr.query();
        if (attachGr.next()) {

            var attachName = attachGr.file_name;
            var attachDate = attachName.match((/\d+/));
            var newName = attachDate + '_' + exportSetName + '.csv';
        }

        var jspr = new JavascriptProbe(this.midServer);
        jspr.setName('FileNameChange'); // This can be any name 
        jspr.setJavascript('var ddr = new MidServer_script_include(); res = ddr.execute();');
        jspr.addParameter("verbose", "true");
        jspr.addParameter("skip_sensor", "true"); // prevent Discovery sensors running for the ECC input
        jspr.addParameter("filename", this.filePath + "\\" + attachName);
        jspr.addParameter("filePath", this.filePath);
        jspr.addParameter("newName", this.filePath + "\\" + newName);
		jspr.addParameter("operation", "rename");
        return jspr.create();

    },

 

Mid Server Script include:

 

initialize: function() {
        /**
         *** Set up the Packages references
         **/
        this.File = Packages.java.io.File;
        this.FileOutputStream = Packages.java.io.FileOutputStream;
        this.FileInputStream = Packages.java.io.FileInputStream;
        this.Path = Packages.java.nio.file.Path;
        this.Paths = Packages.java.nio.file.Paths;
        this.Files = Packages.java.nio.file.Files;
        this.StandardCopyOption = Packages.java.nio.file.StandardCopyOption;

        /**
		/* Set up the parameters
 		**/
        this.verbose = probe.getParameter("verbose");
        this.filePath = probe.getParameter("filePath");
        this.filename = probe.getParameter("filename");
        this.operation = probe.getParameter("operation");
        this.newName = probe.getParameter("newName");
        result = "initialize complete";
    },

    execute: function() {
        if (this.operation == 'rename') {
            this.fileRename(this.filename, this.newName);
        }
        return result;
    },

    fileRename: function(fileName, newName) {
		result+= "\r\n Renaming file.";
        this._debug(result);
        try {
            var res = this._moveFile(fileName, newName);
        } catch (e) {
            result += "\r\n Erro no renomeamento do ficheiro: " + e;
            this._debug(result);
        }
    },

    _moveFile: function(initialPath, targetPath) {
        try {
            this._debug("Initiating file move function");
            var inPath = this.Paths.get(initialPath);
            var tgPath = this.Paths.get(targetPath);
            var res = this.Files.move(inPath, tgPath, this.StandardCopyOption.REPLACE_EXISTING);

            result += "File successfully moved from: " + initialPath + " to: " + targetPath + " \r\n Result: " + res;
            this._debug(result);
        } catch (e) {
            this._debug('Error:' + e);
        }
    },

    _debug: function(m) {
        if (this.verbose == "true") {
            ms.log("::: Mid Server script include logger ::: " + m);
        }
    },

 

This functionality will be called in the after script in the Scheduled Data Export.

 

 

 

View solution in original post

6 REPLIES 6

Appli
Mega Sage
Mega Sage

Hi Frank

May be you can change the name of target file in the Export Set? Just go to System Export Sets -> Administration -> Export Sets, open your Export Set' record and change the File name there to "datetime_file_name".

Hope it helps

Hope it helps

Hello there,

 

If I were to do the exports manually, that would work but the timestamps for the scheduled exports are placed automatically by the system at the end of the filename.

Hi Frank, timestamps are added if Append timestamp checkbox is ticked in Export Set.

find_real_file.png

Please consider to uncheck it there, save and try again with updated file name.

Hope it helps

 

Hope it helps

dabi
Giga Guru

Use Java (First two links) initiated by a JavaScriptProbe (third link). The third link also provides context on how to initiate Java in ServiceNow-terms.

Java Examples - Rename a File: 
https://www.tutorialspoint.com/javaexamples/file_rename.htm

java.io.File ... renameTo(File dest): 
Renames the file denoted by this abstract pathname.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File)

JAVASCRIPTPROBE AND MID SERVER SCRIPT INCLUDES: 
http://www.john-james-andersen.com/blog/service-now/javascriptprobe-and-mid-server-script-includes.h...

Archive.org links if any are down:
https://web.archive.org/web/20210319170809/https://www.tutorialspoint.com/javaexamples/file_rename.h...
https://web.archive.org/web/20200218032142/http://www.john-james-andersen.com/blog/service-now/javas...