VBSCRIPT: Ignore files created today - javascript

I am running an program that uni-directly copies from source to destination. The following script runs in conjunction and skips any files with a "date modified" equaling the same day the program is running.
I'd like to modify the script to skip any files with a "created" date equaling today's date and allow any other files regardless of "modified" date.
Essentially, If DateCreated=Today Then Skip
Below is the script I am currently using. I just can not get the right syntax to use creation time verses modified time.
Thank you in advance,
Function Description(ScriptType)
Description = "Ignores any source files modified today. Not used on Restore."
ScriptType = 2
End Function
Sub RunBeforeFileCompare(Filename, ByRef Skip)
' Ignore if this is a Restore
If SBRunning.Restore Then Exit Sub
' See if the file date is the same as todays date, skip if so
If DateDiff("d", SBRunning.GetFileDateTime(Filename, TRUE), Date) = 0 Then
Skip = TRUE
Else
Skip = FALSE
End If
End Sub

The following example illustrates the use of the GetFile method.
filespec: Required. The filespec is the path (absolute or relative) to a specific file.
An error occurs on GetFile method if the specified file does not exist.
JScript
function ShowFileAccessInfo(filespec)
{
var fso, fle, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
fle = fso.GetFile(filespec);
s = fle.Path.toUpperCase() + "<br>";
s += "Created: " + fle.DateCreated + "<br>";
s += "Last Accessed: " + fle.DateLastAccessed + "<br>";
s += "Last Modified: " + fle.DateLastModified
return(s);
}
VBScript
Function ShowFileAccessInfo(filespec)
Dim fso, fle, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set fle = fso.GetFile(filespec)
s = fle.Path & "<br>"
s = s & "Created: " & fle.DateCreated & "<br>"
s = s & "Last Accessed: " & fle.DateLastAccessed & "<br>"
s = s & "Last Modified: " & fle.DateLastModified
ShowFileAccessInfo = s
End Function

Related

Invalid ICS file and adding time to existing timestamp in Javascript

It's my first time working with ICS files and I'm having trouble getting it to work:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//test.com//NONSGML v1.0//EN
BEGIN:VEVENT
UID:test#test.com
ATTENDEE;CN=My Self ;RSVP=FALSE
DTSTAMP:TZID=Australia/Sydney:19700101T100000
DTSTART:19700101T100000
DTEND:19700101T100000
LOCATION:Online
SUMMARY:Test Title 10.0
DESCRIPTION:-
END:VEVENT
END:VCALENDAR
Not sure if this matters but this is how I've formatted it in Javascript:
var icsFile = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//test.com//NONSGML v1.0//EN\nBEGIN:VEVENT \nUID:test#test.com\nATTENDEE;CN=My Self ;RSVP=FALSE\nDTSTAMP:"+ dtstamp +"\nDTSTART:" + start + " \nDTEND:" + start + "\nLOCATION:" + location + "\nSUMMARY:" + summary + "\nDESCRIPTION:" + description + "\nEND:VEVENT\nEND:VCALENDAR";
When I run it in the ics validator: https://icalendar.org/validator.html
I get:
Error
Invalid DTSTAMP value, must be a valid date-time value near line # 4
Reference: 3.3.5. Date-Time
Question 1
When I check DTSTAMP, it's correct based on Form#3 : https://icalendar.org/iCalendar-RFC-5545/3-3-5-date-time.html
Question 2
How do I go about adding 3 hours into the DTEND timestamp in Javascript?
Thanks!
To fix the validation error, you need a semicolon after DTSTAMP instead of a colon:
DTSTAMP;TZID=Australia/Sydney:19700101T100000

Pass vbscript variables to a JavaScript string

I have a vbscript that I use in Illustrator. In order to save my file as a TIFF I need to use JavaScript. With complete paths the JS script section works fine but when I try to change them to variables('NewState" and 'NewSection' via user input), it's a no go. Nubie to JS so how to insert those variables?
Here's is my latest attempt (FYI - in Illustrator, to use JS inside VBS one must execute it as a String as shown below).
Set App = CreateObject("Illustrator.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim SourceFolder, DestFolder, NewState, NewSection
Call GetNewInputs()
Sub GetNewInputs()
NewState = UCase(InputBox("Current STATE or REGION to be processed.", _
"STATE or REGION", "SOCAL"))
NewSection = ("Section_" & InputBox("INPUT SECTION NUMBER: Section_YY", _
"Input Section", "32"))
Set SourceFolder = FSO.GetFolder("S:\" & NewState & "\" & NewSection & "\Road DXFs")
DestFolder = "S:\" & NewState & "\" & NewSection & "\Light TIFFs\"
End Sub
App.DoJavaScript("function test(){var doc = app.activeDocument;var destFile = new File(""/s/" + <%=NewState%> + "/" + <%=NewSection%> + "/Light TIFFs/SOCAL_CN68_resx.tif"");var type = ExportType.TIFF;var opts = new ExportOptionsTIFF();opts.imageColorSpace=ImageColorSpace.GrayScale;opts.resolution=72;opts.antiAliasing=AntiAliasingMethod.ARTOPTIMIZED;opts.IZWCompression=false;opts.saveMultipleArtboards=true;opts.artboardRange=""1"";doc.exportFile(destFile, type, opts);}test();")
MyDoc.Close(2)

Compare timestamp in two different formats - GAS

I am using the enhanced workflow script that was posted by Mogsdad here.
I have managed to work out a few issues but one that I am stuck on at the moment is the error that comes up from this section -
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, timestamp);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
I get the "Request not available" error because the ArrayLib.indexOf object is comparing the time stamp that is being presented from the same source but via two different 'routes'.
The timestamp from the 'timestamp' variable looks like this - "17/03/2015 18:00:11"
...and the timestamp contained in the 'data' variable (that should match the timestamp variable) looks like this - "Tue Mar 17 2015 00:30:10 GMT-0700 (PDT)".
I am assuming that the two different formats is what is resulting in the ArrayLib.indexOf object returning a '-1' result and hence the error message.
Any thoughts on what I need to do to get the matching working successfully ?
Create a new Date object for the timestamp value, so that you can ensure they can be compared. The code should look like:
var dateFromTimestamp = new Date(timestamp);
After looking around at a few other posts I came up with a solution that seems to work pretty well and overcomes the issues with using the timestamp.
I put an array formula in the first column of the response sheet that created a ticket number -
=ArrayFormula(if(B2:B,"AFR"&text(row(A2:A)-1,"00000"),iferror(1/0)))
Then I retrieved the ticket number (var cellVal) and sent it with the email. The response email brings the approval value to the correct line every time....so far.
function sendEmail(e) {
// Response columns: Timestamp Requester Email Item Cost
var email = e.namedValues["Requester Email"];
var item = e.namedValues["Item"];
var cost = e.namedValues["Cost"];
//var timestamp = e.namedValues["Timestamp"];
var row = e.range.getRow();
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1pFL0CEW5foe8nAtk0ZwwTleYrBn2YulMu_eKPDEFQaw').getSheetByName("Form Responses 1");
var range = sheet.getDataRange();
var cellval = range.getCell(row,1).getValue();
//var origMail = range.getCell(row,3).getValue();
Logger.log(cellval);
//Logger.log(origMail);
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["Requester Email"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+row+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+row+'&cellval='+cellval;
var html = "<body>"+
"<h2>Please review</h2><br />"+
"Request from: " + email + "<br />"+
"Ticket No: " + cellval + "<br />"+
"For: "+item +", at a cost of: $" + cost + "<br /><br />"+
"Approve<br />"+
"Reject<br />"+
"</body>";
MailApp.sendEmail(Session.getEffectiveUser().getEmail(),
"Approval Request",
"Requires html",
{htmlBody: html});
}

Recursive processing of a directory not working correctly

I've been combing this forum looking at other examples of code similar to mine but I still have not been able to solve the issue.
I am processing images in Fiji/imageJ using a macro code. The code is meant to recursively search a given directory for image files (in this case .vsi files) and convert them to .tiff using the built in bioformats functions.
I have cobbled the following code together from several examples (I am not a programmer, I have a biology degree), and I am returning an error that the specified file does not exist just as I am about to actually process a file.
All of my images have the following general directory structure:
~/Brain_01/Slice_01/Slice_01_01.vsi
An actual example is as follows for the second image in this set:
~/K259_tlx3cre/K259_1of3_02/K259_1of3_01_02.vsi
I really, really appreciate all the help you guys provide! I am completely stuck right now and am just banging my head against the keyboard at this point. Also, I think I've followed all the rules for posting. If not please just point out the error of my ways.
Finally here is the macro code I have written so far:
Dialog.create("File type");
Dialog.addString("File suffix: ", ".vsi", 5);
Dialog.show();
suffix = Dialog.getString();
inDir = getDirectory("Choose Directory Containing " + suffix + " Files ");
outDir = getDirectory("Choose Directory for TIFF Output ");
setBatchMode(true);
processFiles(inDir, outDir, "");
print("Done!");
function processFiles(inBase, outBase, sub) {
flattenFolders = false; // this flag controls output directory structure
print("Processing folder: " + sub);
list = getFileList(inBase + sub);
if (!flattenFolders) File.makeDirectory(outBase + sub);
for (i=0; i<list.length; i++) {
path = sub + list[i];
//upath = toUpperCase(path);
upath = path; //the previous line cause some problems
if (endsWith(path, "/")) {
processFiles(inBase, outBase, path);
}
else if (endsWith(upath, suffix)) {
print("Importing " + suffix + " = " + list[i]);
run("Bio-Formats Windowless Importer", "open=path color_mode=Default view=Hyperstack stack_order=XYCZT");
print("Blue...");
selectImage(1);
title1 = getTitle();
run("Blue");
print("Green...");
selectImage(2);
title2 = getTitle();
run("Green");
print("Red...");
selectImage(3);
title3 = getTitle();
run("Red");
print("Merging Channels...");
run("Merge Channels...", "red=&title3 green=&title2 blue=&title1 gray=*None* cyan=*None* magenta=*None* yellow=*None* create keep");
print("Converting to RGB");
run("RGB Color");
saveAs("Tiff", path);
run("Close All");
}
}
}
Thanks to some great help from Jan, and the people on the ImageJ mailing list, I was able to get my code working well enough to do what I need to do! The code below is working well enough to batch convert a directory full of .vsi files to .tiff using the functions I need. I haven't tried changing my code to Michael's suggestion to change endsWith(path, "/"... if i get that working in the future I will post it also.
Dialog.create("File type");
Dialog.addString("File suffix: ", ".vsi", 5);
Dialog.show();
suffix = Dialog.getString();
inDir = getDirectory("Choose Directory Containing " + suffix + " Files ");
outDir = getDirectory("Choose Directory for TIFF Output ");
setBatchMode(true);
processFiles(inDir, outDir, "");
print("Done!");
function processFiles(inBase, outBase, sub) {
flattenFolders = true; // this flag controls output directory structure
print("Processing folder: " + sub);
list = getFileList(inBase + sub);
if (!flattenFolders) File.makeDirectory(outBase + sub);
for (i=0; i<list.length; i++) {
path = sub + list[i];
//upath = toUpperCase(path); only need if the file extension is case sensitive
upath = path; //avoids the previous line
if (endsWith(path, "/")) {
processFiles(inBase, outBase, path);
}
else if (endsWith(upath, suffix)) {
print("Importing " + suffix + " = " + list[i]);
run("Bio-Formats Windowless Importer", "open=["+inBase + path+"] color_mode=Default view=Hyperstack stack_order=XYCZT");
print("Stack to Images...");
run("Stack to Images");
print("Blue...");
selectImage(1);
title1 = getTitle();
run("Blue");
print("Green...");
selectImage(2);
title2 = getTitle();
run("Green");
print("Red...");
selectImage(3);
title3 = getTitle();
run("Red");
print("Merging Channels...");
run("Merge Channels...", "red=&title3 green=&title2 blue=&title1 gray=*None* cyan=*None* magenta=*None* yellow=*None* create keep");
print("Converting to RGB");
run("RGB Color");
saveAs("Tiff", outBase + path);
run("Close All");
}
}
}
By looking at the error message you get, you should be able to spot the issue: while your file sits at e.g. inBase + sub + list[i], your path variable contains just sub + list[i]. So you should use something like:
run("Bio-Formats Windowless Importer", "open=[" + inBase + path + "] color_mode=Default view=Hyperstack stack_order=XYCZT");
for opening the file, and:
saveAs("Tiff", outBase + path);
for saving the output file.
If you also want to use the flattenFolders flag in your code, you should build your output path dependent on the state of flattenFolders, such as:
outputPath = outBase;
if (!flattenFolders) outputPath += sub;
outputPath += list[i];
By the way, there's no need to convert your path to uppercase with toUpperCase(path), unless you want to use a case-insensitive file suffix. In that case, you can write:
if (endsWith(toUpperCase(path), toUpperCase(suffix))) {
// process your file here
}
to allow both .vsi and .VSI as an input.
Note: The script editor of the Fiji distribution of ImageJ offers a macro template to process folders recursively, you can open it via Templates > Macros > Process Folder in the editor.

Quicker searching in JScript using the Bash

I am using the following JScript code to search for a string inside a file:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
while(!myFile.IsEndOfFile())
{
s = myFile.ReadLine();
if (aqString.Find(s, searchString) != -1)
Log.Checkpoint(searchString + " found.", s);
}
myFile.Close();
This is rather slow. I was thinking about using bash commands in order to speed up the search in file process:
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("C:\\cygwin\\bin\\bash.exe -c 'cat \"" + folderName + "/" + fileName + "\"'");
while (!oExec.StdOut.AtEndOfStream)
Log.Checkpoint(oExec.StdOut.ReadLine());
while (!oExec.StdErr.AtEndOfStream)
Log.Error(oExec.StdErr.ReadLine());
Since every time bash.exe is started a new window opens the searching is not faster than before. Is there a possibility to have the bash run in the background using another switch?
Every invocation of WshShell.Exec will start a new process which is costly. If your textfile is not too big this will prevent spawning a new process:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
var myFileData = myFile.Read(myFile.Size);
var index = myFileData.indexOf(searchString);
if(index>0)
{
Log.Checkpoint(searchString + " found.", index);
}
myFile.Close();
This will not print the whole line but the index of the found location. If you want the whole line, search for line endings from there.

Categories