Patrick
Patrick

Reputation: 39

Windows Batch File and an FTP Datestamp

I am struggling to grasp the concept of writing batch files. I am hoping to schedule a .bat file to download a file with a timestamp on a daily basis. Setting up the scheduled task etc. is straight forward, my problem arises when I try execute the code to take the fixed part of the filename and append a datestamp to identify the appropiate file.

From the research I have done I still cannot get my code to pick up yesterday date in a YYYYMMDD format. eg. today is the 15th of August, I would like my batch to identify the file with 20130814. My exisitng (static) ftp batch code is

option confirm off
option batch abort
open Ftp_name
lcd "U:\XXXX\YYYY\ZZZZ"

get "LoanSummary__Daily.xlsx"

Whereas I would like the batch to consider..

get "LoanSummary__Daily_" & YYYYMMDD & ".xlsx"

Thanks.

Upvotes: 0

Views: 2476

Answers (1)

dbenham
dbenham

Reputation: 130819

I don't think you can dynamically build file names within an FTP script. But you can dynamically build the ftp script with a batch file prior to invoking it.

The simplest way to do this is to create an ftp script template that has the variable portion(s) represented as an environment variable with delayed expansion. For example !yesterday! could refer to an environment variable that gets expanded into yesterday's date. A simple FOR /F loop reads the template, and writes each line to a new ftp script file. The variables are automatically expanded in the process as long as delayed expansion is enabled.

Getting yesterday's date in a Windows batch file is a non-trivial excercise. There have been many methods posted on SO as well as other sites. Most methods have various limitations, the most common of which is susceptability to problems due to differences in locale date formatting. I use a hybrid batch/JScript utility called getTimestamp.bat that will work on any Windows platform from XP onward, regardless of the locale. It is pure script, so no .exe download is needed. getTimestamp.bat is avaiable here.

Assuming getTimestamp.bat is in you current directory, or better yet, somewhere within your PATH, then the following should work.

getYesterday.ftp.template

option confirm off
option batch abort
open Ftp_name
lcd "U:\XXXX\YYYY\ZZZZ"

get "LoanSummary__Daily_!yesterday!.xlsx"

getYesterday.bat

@echo off
setlocal enableDelayedExpansion

:: Get yesterday's date in YYYYMMDD format
call getTimestamp -od -1 -f {yyyy}{mm}{dd} -r yesterday

:: Create a temporary ftp script that uses the "yesterday" date
>temp.ftp (for /f "delims=" %%L in (getYesterday.ftp.template) do echo %%L)

:: Now simply invoke your ftp client using the temp script, something like
ftp -s:temp.ftp ...

:: Delete the temporary ftp script
del temp.ftp

Upvotes: 1

Related Questions