This is an old revision of the document!
Useful Scripts
Advertisement
Checking file existence
WinSCP .NET assembly mostly deprecates techniques demostrated in this article. Using the assembly is now preferred approach for advanced automation tasks with WinSCP.
You may use following Windows script host JavaScript code (example.js
):
// Configuration // Remote file search for var FILEPATH = "/home/user/myfile.dat"; // Session to connect to var SESSION = "session"; // Path to winscp.com var WINSCP = "c:\\program files\\winscp\\winscp.com"; var filesys = WScript.CreateObject("Scripting.FileSystemObject"); var shell = WScript.CreateObject("WScript.Shell"); var logfilepath = filesys.GetSpecialFolder(2) + "\\" + filesys.GetTempName() + ".xml"; var p = FILEPATH.lastIndexOf('/'); var path = FILEPATH.substring(0, p); var filename = FILEPATH.substring(p + 1); var exec; // run winscp to check for file existence exec = shell.Exec("\"" + WINSCP + "\" /log=\"" + logfilepath + "\""); exec.StdIn.Write( "option batch abort\n" + "open \"" + SESSION + "\"\n" + "ls \"" + path + "\"\n" + "exit\n"); // wait until the script finishes while (exec.Status == 0) { WScript.Sleep(100); WScript.Echo(exec.StdOut.ReadAll()); } if (exec.ExitCode != 0) { WScript.Echo("Error checking for file existence"); WScript.Quit(1); } // look for log file var logfile = filesys.GetFile(logfilepath); if (logfile == null) { WScript.Echo("Cannot find log file"); WScript.Quit(1); } // parse XML log file var doc = new ActiveXObject("MSXML2.DOMDocument"); doc.async = false; doc.load(logfilepath); doc.setProperty("SelectionNamespaces", "xmlns:w='http://winscp.net/schema/session/1.0'"); var nodes = doc.selectNodes("//w:file/w:filename[@value='" + filename + "']"); if (nodes.length > 0) { WScript.Echo("File found"); // signalize file existence to calling process; // you can also continue with processing (e.g. downloading the file) // directly from the script here WScript.Quit(0); } else { WScript.Echo("File not found"); WScript.Quit(1); }
Advertisement
Run the script with command:
cscript /nologo example.js
Following batch file shown how to continue with processing based on file exitence:
cscript /nologo example.js if errorlevel 1 goto error echo File exists, do something rem Do something exit :error echo Error or file not exists
Alternatively you can continue with the processing directly in JavaScript code as suggested by respective comments.
Other Examples
- Guide to scripting/automation;
- Guide to advanced scripting;
- See WinSCP .NET assembly examples for advanced tasks.
Other Examples
- Guide to scripting/automation;
- Guide to advanced scripting;
- See WinSCP .NET assembly examples for advanced tasks.
Advertisement