Handy ETL JScript

import.cmd: @cscript /b import.js %*

import.js
  1. //v1.0
  2.  
  3. function cleanarg(i)
  4. {
  5.   //WScript.stdout.WriteLine("i: " + i);
  6.   return(WScript.Arguments(i+1).replace("\"", ""));
  7. }
  8.  
  9. //WScript.stdout.WriteLine("arg count: "+WScript.Arguments.length);
  10.  
  11. if (WScript.Arguments.length == 0)
  12. {
  13.   WScript.stderr.WriteLine("Usage:");
  14.   WScript.stderr.WriteLine("  -i \"input file\"");
  15.   WScript.stderr.WriteLine("  -o \"output file\" (blank = screen output)");
  16.   WScript.stderr.WriteLine("  -r \"record separator\"");
  17.   WScript.Quit();
  18. }
  19.  
  20. var inputfile;
  21. var outputfile;
  22. var record;
  23.  
  24. var localpath = WScript.ScriptFullName.replace(WScript.ScriptName, "");
  25.  
  26. for (var i = 0; i < WScript.Arguments.length; i++)
  27. {
  28.   //WScript.stdout.WriteLine("arg["+i+"]: "+WScript.Arguments(i));
  29.   switch (WScript.Arguments(i))
  30.   {
  31.     case "-i": inputfile = cleanarg(i); break;
  32.     case "-o": outputfile = cleanarg(i); break;
  33.     case "-r": record = cleanarg(i); break;
  34.   }
  35. }
  36.  
  37. var fso = new ActiveXObject("Scripting.FileSystemObject");
  38.  
  39. //WScript.stderr.WriteLine("  inputfile: " + inputfile + ", record: " + record + ", exension: " + fso.GetExtensionName(inputfile) + ", WScript.ScriptFullName: " + WScript.ScriptFullName.replace(WScript.ScriptName, ""));
  40. //WScript.Quit();
  41.  
  42. var ForReading = 1, ForWriting = 2;
  43.  
  44. var f = fso.OpenTextFile(inputfile, ForReading);
  45.  
  46. var out = WScript.stdout;
  47. if (outputfile != undefined) out = fso.OpenTextFile(outputfile, ForWriting, true);
  48.  
  49. var line="";
  50. while ( f.AtEndOfStream != true )
  51. {
  52.   var str = f.Readline();
  53.   if (str == record)
  54.   {
  55.     out.WriteLine(line.slice(1));
  56.     line = "";
  57.   }
  58.   else line += "," + str;
  59. }
  60. out.Close();
  61.  
  62. if (fso.GetExtensionName(outputfile) == "csv")
  63. {
  64.   var WshShell = WScript.CreateObject("WScript.Shell");
  65.   //WScript.stderr.WriteLine(localpath + outputfile);
  66.   WshShell.Run(localpath + outputfile);
  67.   WshShell.Run(localpath + outputfile);
  68.   WshShell.Run(localpath + outputfile);
  69. }