Using VBA to run WinSCP script - excel

I am able to download files from SFTP in CMD window, by using following code:
WinSCP.com
# Connect to the host and login using password
open user:pw#address
# get all the files in the remote directory and download them to a specific local directory
lcd C:\Users\xx\Desktop
get *.xlsx
# Close and terminate the session
exit
I searched online and found out that I can put these codes in a bat file and use
Call Shell("cmd.exe /c C:\Users\xx\Desktop\WinSCPGet.bat", 1)
However, only the first line of the bat file WinSCP.com is being executed. It will pop up the cmd window, showing this, without doing anything else.
How to execute all the lines at one time?
Thanks

The code you have is not a Windows batch file. It's one Windows command followed by WinSCP commands. The first command runs winscp.com application, which then sits and waits for input. If you eventually close it, Windows command interpreter (cmd.exe) will carry on executing the remaining commands, failing most, as they are not Windows commands. See also WinSCP script not executing in batch file and WinSCP FAQ Why are some WinSCP scripting commands specified in a batch file not executed/failing?
So you either have to save the commands (open to exit) to a WinSCP script file (say script.txt) and execute the script using the /script switch:
Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt")
Alternatively, specify all commands on WinSCP command line, using the /command switch:
Call Shell("C:\path\winscp.com /ini=nul /command ""open user:pw#address"" ""lcd C:\Users\xx\Desktop"" ""get *.xlsx"" ""exit""")
Regarding the quotes: With the /command switch, you have to enclose each command to double-quotes. In VBA string, to use a double-quote, you have to escape it by doubling it.
Also note that you generally should use the /ini=nul switch to isolate the WinSCP script run from your WinSCP configuration. This way you can also make sure that the script will run on other machines. Your script won't, as it lacks the -hostkey switch to verify the SSH host key fingerprint. Using the /ini=nul will help you realize that.
You can have WinSCP GUI generate complete command-line (including the -hostkey) for you.
See also Automating file transfers to SFTP server with WinSCP.

I like this small and compact procedure, and use it in my own projects. No temp-files required. Fast and reliable.
Parse a string src (an absolute filepath) to uploadImageByFTP. Etc. C:\Users\user\Desktop\image.jpg, and the file will be uploaded.
Replace:
<username> with FTP-User
<password> with FTP-Password
<hostname> with FTP-hostname (etc. example.com)
<WinSCP.com path> with path on your WinSCP-client (etc. C:\Program Files (x86)\WinSCP\WinSCP.com. Caution: WinSCP.com and not WinSCP.exe)
<FTP-path> with path on your FTP-client (etc. /httpdocs/wp-content/uploads)
Sub uploadImageByFTP(src As String)
Dim script As Object: Set script = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
'Not empty
If (src <> vbNullString) Then
'Execute script
script.Run _
"""<WinSCP.com path>"" " + _
"/ini=nul " + _
"/command " + _
"""open ftp://<username>:<password>#<hostname>/"" " + _
"""cd <FTP-path>"" " + _
"""put " & """""" & src & """""" & """ " + _
"""close"" " + _
"""exit""", windowStyle, waitOnReturn
End If
End Sub
WScript.Shell is more powerful than the default Shell(), as you can append a waitOnReturn-command; this tells VBA, that further execution isn't allowed before the file(s) have been uploaded to the FTP-server.
Change windowStyle to 0, if you don't like the command prompt to open on each execution.

Related

Applescript if no file is added

I have the following automator apple script that I'm using so that when I drag a file into a dock icon, it opens that file in vim:
on run {input, parameters}
set filename to POSIX path of input
set cmd to "clear && 'vim' '" & filename & "' && exit"
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text cmd
end tell
end tell
end run
However, I would also like to allow clicking the icon itself to open vim without any file, i.e., running $ vim. How would I change the above script so that:
If a filename is passed, I open vim with that file, vim filename
If no filename is passed (the icon is just double-clicked), it just opens vim, with vim ?
The following example AppleScript code will do as you've asked; however, keep in mind that input is a list and as presently coded it is expecting a single item list, meaning you've only dragged and dropped one file onto the app's Dock Tile:
on run {input, parameters}
if not input is equal to {} then
set filename to POSIX path of first item of input
set cmd to "clear && 'vim' '" & filename & "' && exit"
else
set cmd to "clear && 'vim' '" & "' && exit"
end if
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
write text cmd
end tell
end tell
end run
Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.

Shell command on Excel with long path name don't work

I have a batch file run.bat in a network folder "L:\Common Data\myfile" and i want to execute it from an Excel's macro.
Googling around I found these sintax:
Call Shell(Environ$("COMSPEC") & " /k L:\Common Data\myfile\run.bat", vbNormalFocus)
but it fails because it reads only "L:\Common".
I tryed many suggestion found on Internet but no one succeeded.
Someone have a solution?
Path names with spaces have to be wrapped in quotes.
Call Shell(Environ$("COMSPEC") & " /k ""L:\Common Data\myfile\run.bat""", vbNormalFocus)

Setup.exe creation in InstallShield

This is my function to remove the directory after uninstalling.
Basically, in my .ism file, there are 2 .rul files(setup.rul and VerGetFileProperty.rul). I have added some code to clean the directory in setup.rul. I build, and one setup.exe is formed. While I run setup.exe, it will ask me to select the db, if I select a db, its says the db server is not found. But if I run the original setup, it will auto detect db server and install. How is the setup.exe getting created? I haven't made any changes on searching for db server part. I have just created a function to remove the directory while uninstalling.
function fnClean()
NUMBER nrv;
begin
if (ExistsDir (INSTALLDIR ^ "XYZ Dir") = EXISTS) then
SetDialogTitle(DLG_ASK_YESNO,"Delete Logs");
nrv = AskYesNo( "Do you want to delete all log files now? Say No if you prefer delete them later manually.", YES );
if ( nrv ) then
nrv = DeleteDir (INSTALLDIR ^ "XYZ Dir", ALLCONTENTS);
DeleteDir (INSTALLDIR, ALLCONTENTS);
endif;
else
DeleteDir (INSTALLDIR, ALLCONTENTS);
endif;
end;
I assume your installer either calling some exe that is generating the log files, or the log files are generated by using whatever application you are installing.
If you are using an MSI(Windows Installer) based project, you can add the files to the RemoveFile table. You'll want to use a InstallMode of 2 (remove on uninstall)
editing to expand answer
cmd_line = "cmd /c """ & objNamedArgs.Item("SQLCMD") & """ " & objNamedArgs.Item("CONNECT") & _" -i " & sql_file & " > " & log_file & " 2>&1"
-i "sqlfile" is an argument to the sqlcmd program. -i means "input" and the sqlfile will be whatever is being specified, usually a .sql script.
logfile means: redirect output of whatever command (in this case, sqlcmd) into the file specified by logfile.
The 2>&1 is already answered here.

How do I write to a text file using AppleScript?

So, that's it. How can I write to a text file using AppleScript?
I've tried googling around, but answers seem to be years old and I'm not really sure what should be the preferred idiom this days.
on write_to_file(this_data, target_file, append_data) -- (string, file path as string, boolean)
try
set the target_file to the target_file as text
set the open_target_file to ¬
open for access file target_file with write permission
if append_data is false then ¬
set eof of the open_target_file to 0
write this_data to the open_target_file starting at eof
close access the open_target_file
return true
on error
try
close access file target_file
end try
return false
end try
end write_to_file
Interfacing with it can be cleaned up with the following...
my WriteLog("Once upon a time in Silicon Valley...")
on WriteLog(the_text)
set this_story to the_text
set this_file to (((path to desktop folder) as text) & "MY STORY")
my write_to_file(this_story, this_file, true)
end WriteLog
A short version in pure AppleScript:
set myFile to open for access (choose file name) with write permission
write "hello world" to myFile
close access myFile
It seems there is no native one command solution. Instead you have to open and later close the file.
#JuanANavarro.
When using the shell you should use quoted form of for the TEXT and the file path.
This will help stop errors with spaces in file names and characters like apostrophes in the text for example.
set someText to "I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell."
set textFile to "/Users/USERNAME/Desktop/foo.txt"
do shell script "echo " & quoted form of someText & " > " & quoted form of textFile
The above script works fine.
If I did not have & quoted form of someText
but instead I had & someText I would get the following error.
error "sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file" number 2
The apostrophes in "I've" is seen as part of the command.
If I had
set textFile to "/Users/USERNAME/Desktop/some foo.txt" as my file path ( note the space.) And did not have & quoted form of textFile but instead I had & textFile
Then when the file was written out it would write to a file named "some" and not "some foo.txt"
I've also learned that a quick hack, if one only wants to spit a bit of text to a file, is to use the shell.
do shell script "echo TEXT > some_file.txt"
For me running do shell script was too slow on a PowerBook G4 when executed in a loop 300000 times ;), but of course that's quicker to write which sometimes makes sense. You would also want to escape shell characters like this:
do shell script "echo " & quoted form of foobar & " >> some_file.txt"
and for aesthetic reasons I would use
tell me to do shell script "#..."
but I haven't verified yet (what I believe) that if "do shell script" is in a block of "tell Finder" for example it is Finder process that creates a subshell. With "tell me to do shell script" at least Script Editor log looks better for me. ;)

use winrar command line to create zip archives

I'm using the following winrar command line to create zip archives:
rar.exe a -df -ep -ag[yyyyMMddhhmmss] -ms[txt] C:\MyZipFile.zip C:\tmp\MyFiles*.txt
The archives created are in RAR format instead of ZIP. Is there a way to create regular ZIP and not RAR archives?
Make certain you are using WinRAR.exe and not Rar.exe.
If you are using the command line to do this make sure you type:
winrar a -afzip c:\test.zip c:\test.csv
not:
a -afzip c:\test.zip c:\test.csv
It works for me. I also got it to work in SSIS.
WinRAR has a detailed description of its command line syntax in its help files (WinRAR Help), chapter "Command line syntax".
All the commands such as "a" (add to an archive), "d" (delete from an archive), "e" (extract from an archive ignoring paths) and switches such as "-af" (specify whether to create a rar or a zip file), "-ad" (append archive name to destination path) or "-p" (encrypt the archive using password protection) are listed there.
There are quite a lot of options. I recommend reading the command line syntax rules when working with WinRAR via command lines.
In order to trigger WinRAR zip-packaging from within a MS Access database application, I use in the VBA code for example
Shell c:\Programme\WinRAR\winrar.exe a -afzip -p <AnyPasswordYouLike> "e:\MyStuff\TargetFolder\Output.zip" "e:\MyStuff\SourceFolder\Input.docx"
Of course, the file paths and names are ususally entered via variables, e.g. like
Dim strWinrarCommandline As String
'... and the other variables as well declared in advance, of course...
strWinrarCommandline = strWinrarPathAndSwitches & "-p" & strPassword & " " & Chr(34) & strOutputFullName & Chr(34) & " " & Chr(34) & strInputFullName & Chr(34)
'And then call Winrar simply by:
Shell strWinrarCommandline
So rar.exe is currently unable to create zip files by itself only by calling in the Windows version it is possible.

Resources