2

I have this script in a batch file that uploads a local file to our FTP server. I need to rename myfile.csv to suffix the date and time in this format YYYYMMDDHHMM e.g. myfile_201701041333.csv. How can this be done?

@Echo Off
Set _FTPServerName=myserver
Set _UserName=myusername
Set _Password=mypassword
Set _LocalFolder=\\data\myfolder
Set _RemoteFolder=e-download
Set _Filename=myfile.csv
Set _ScriptFile=ftp1
:: Create script
 >"%_ScriptFile%" Echo open %_FTPServerName%
>>"%_ScriptFile%" Echo %_UserName%
>>"%_ScriptFile%" Echo %_Password%
>>"%_ScriptFile%" Echo lcd %_LocalFolder%
>>"%_ScriptFile%" Echo cd %_RemoteFolder%
>>"%_ScriptFile%" Echo binary
>>"%_ScriptFile%" Echo put %_Filename%
>>"%_ScriptFile%" Echo quit
:: Run script
ftp -s:"%_ScriptFile%"
Del "%_ScriptFile%"
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Emma
  • 577
  • 1
  • 13
  • 27
  • ...just a side note: you could put all `echo` command inside of a parenthesised block `( )` and redirect the entire block once by `> "%_ScriptFile%"`... – aschipfl Jan 04 '17 at 14:10
  • Thanks everyone, sorted and working. http://stackoverflow.com/questions/864718/how-to-append-a-date-in-batch-files for required date code. – Emma Jan 04 '17 at 14:11

2 Answers2

4

The put command accepts an optional second argument to specify a target name:

put localfile remotefile

In your batch file that would be:

>>"%_ScriptFile%" Echo put %_Filename% %_Remotename%

To set the %_Remotename% to the timestamped name, see
Format date and time in a Windows batch script – Prefer the wmic or PowerShell-based solutions, as the %date%-based solutions are not locale independent.


Your task would be a way more easier with some more advanced FTP client.

For example with WinSCP FTP client it's as easy as:

@Echo Off
Set _FTPServerName=myserver
Set _UserName=myusername
Set _Password=mypassword
Set _LocalFolder=\\data\myfolder
Set _RemoteFolder=e-download
Set _Filename=myfile.csv

winscp.com /ini=nul /command ^
    "open ftp://%_UserName%:%_Password%@%_FTPServerName%/" ^
    "put ""%_LocalFolder%\%_Filename%"" ""%_RemoteFolder%/myfile_%%TIMESTAMP#yyyymmddhhnn%%.csv""" ^
    "exit"

References:

(I'm the author of WinSCP)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

Using the command wmic os get localdatetime /value you can get an ouput that almost directly suits your desire. Now with some extra code you can trim it to your perfect fit:

@echo off
setlocal EnableDelayedExpansion
for /f "delims=.= tokens=2" %%n in ('wmic os get localdatetime /value') do (
set var=%%n
set var=!var:~0,-2!
)
echo %var%

For every output in the command above take the text between = and .. Save that text to the variable var, trim the last 2 characters to remove the seconds.

Now you can do something like:

ren myfile.csv myfile_%var%.csv

to rename it.

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54