Run a program in a batch script and wait for it to finish before continuing
I have a very specific requirement. I am attempting to upload files via sftp which uses private keys. I already have a bat file that connects to the host and uploads the file however I need to move the uploaded files once completed to another path.
The first bat file is called start.bat
. This connects to the sftp server and uploads the file. I am using winscp to connect to the host.
The second bat file is called done.bat
. This moves files from one directory to another.
I am calling the second bat file from the first using call done.bat
. The issue I have is that done.bat
is completed even before the first batch file has had the chance to authenticate, login and upload.
I want to only move the file once the upload has completed. If the upload fails for some reason, the second file doesn't execute.
The bat files are on a Windows XP machine.
use start /wait winscp ...
to start the file transfer, this will pause the batch script until winscp exits, you can add the move commands after that line or call done.bat
start /wait winscp ...
call done.bat
You should combine this with the errorchecking suggested by Mark Allen
Personally I'd use a command line SFTP client (like the one supplied with Putty or OpenSSH) which I think would avoid this sort of issue.
Modify start.bat to detect failure on the part of winscp.exe. Only call done.bat if winscp.exe exits with an exit code of 0.
Try something like this:
winscp.exe blah blah blah
if not errorlevel 0 goto end
call done.bat
:end
Note that I'm only assuming winscp.exe exits with 1 or greater upon error. Check the documentation for winscp.exe.
Editing to include the following:
Let's say winscp.exe doesn't use exit codes to denote success or failure. You might need to do something different.
winscp.exe /log=%temp%\wscpresults.log *other parameters here*
ping -n 300 -w 1000 127.0.0.1 > nul
find /i "success" %temp%\wscpresults.log
if errorlevel 0 goto end
call done.bat
:end
Where:
- The ping command accomplishes nothing but to wait for 5 minutes (300 x 1000ms or 1 second = 5 minutes)
- The /log switch causes winscp.exe to write the results of the operation to a file.
- The find command looks for the word success - I have no idea what winscp actually writes to the file, you'd have to try it once and identify the string that shows everything worked, and then modify the string that find searches for to that.
- If the find command doesn't find the word "success", go to the 'end' label without calling done.bat. Otherwise, we think everything succeeded and we call done.bat.