Can I create a folder with current datetime when I use Windows Command-line FTP - windows

Is there any possibility to create a new directory with current datetime when I use the Windows Command-line FTP?
for more clarification if I have scheduler to run this:
C:\windows\system32\ftp -s:ftpMyFiles.txt
And inside ftpMyFiles.txt I have:
open 127.0.0.1
user
pass
mkdir %DATE%
bye
here is the question Can I create A new directory with a datetime here (mkdir %DATE%)?

You have to generate the ftpMyFiles.txt dynamically like:
(
echo open 127.0.0.1
echo user
echo pass
echo mkdir %DATE%
echo bye
) > ftpMyFiles.txt
C:\windows\system32\ftp -s:ftpMyFiles.txt
Note that the value of %DATE% is locale-specific. So make sure you test your batch file on the same locale you are going to actually run it. Otherwise you may get unexpected results. For example on my (Czech) locale the DATE=po 13. 04. 2015
You can achieve the same easier and more reliably using WinSCP scripting. It supports:
Specifying the commands directly on its command-line
%TIMESTAMP% syntax.
winscp.com /ini=nul /command ^
"open ftp://user:pass#127.0.0.1/" ^
"mkdir %%TIMESTAMP#yyyymmdd%%" ^
"exit"
(I'm the author of WinSCP)

I prefer using ISO 8601 date formats (sometimes minus hyphens), as that makes ordering files by date easier (simply order alphabetically by folder name). Generally, I find ISO 8601 dates with hyphens easier to read than those without, but your requirements may vary.
Also, ISO 8601 avoids the silliness from across the pond where days and months are switched around - this confuses those of us who use international standards no end.
The ISO 8601 format used most often is YYYY-MM-DD or YYYYMMDD (e.g., 2016-02-24 or 20150224 for today's date).
Using wmic os get LocalDateTime, you can get non-locale-specific datetime from the operating system, and then convert it to ISO 8601 format, as demonstrated here:
#echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldtime=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
set ldate=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%
set ldatestraight=%ldt:~0,8%
echo Local datetime is [%ldtime%]
echo Local date is [%ldate%]
echo Local date no hyphens is [%ldatestraight%]
echo .
echo Raw datetime is [%ldt%]
pause
So, taking Martin Prikryl's sample code a step further, you could do something like this (for ISO 8601 dates with hyphens):
(
echo open 127.0.0.1
echo user
echo pass
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldate=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%
echo mkdir %ldate%
echo bye
) > ftpMyFiles.txt
C:\windows\system32\ftp -s:ftpMyFiles.txt
Kudos to Anerty and Jay for their answer to a similar question that helped me a little while back, here.

Related

WHEN MAKE .bat file and run do not work WINDOWS 7

D:\> set "today=%date:~10,4%-%date:~7,2%-%date:~4,2%"
D:\> mkdir SVN_BACKUP_DUMP_TEST\%today%
D:\> CD SVN_BACKUP_DUMP_TEST\%today%
when we are make bat file this command not work
Format of date of referenced environment variable DATE depends on region setting, i.e. which country and derived from country which date format is configured for the current account. So which string is assigned to environment variable today and if that string is valid for a directory or file name depends on account specific date format.
On my computer with German set as country for my account output of echo %DATE% is 13.11.2017. So the date format is dd.MM.yyyy with point as separator, no weekday and always two digits for date and month even for a date or month less than 10.
The command line
echo %DATE:~10,4%-%DATE:~7,2%-%DATE:~4,2%
produces on my machine with my account and my region settings the output:
-01-1.
That is definitely not the current date in format yyyy-MM-dd.
The solution is using following batch code:
#echo off
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "Today=%%I"
set "Today=%Today:~0,4%-%Today:~4,2%-%Today:~6,2%"
mkdir "SVN_BACKUP_DUMP_TEST\%Today%" 2>nul
cd "SVN_BACKUP_DUMP_TEST\%Today%"
This is a region independent solution. The batch code is completely explained in answer on
Why does %date% produce a different result in batch file executed as scheduled task?
What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean? is one more question on which answer should be read to understand the string substitutions. And run in a command prompt window set /? to get displayed the help for command SET explaining string substitution, too.

Rename file with file's date in CMD

I think I've bitten off a lot more than I can chew.
I'm a court reporter, working in the Minnesota court system. We've developed a new policy for filing our electronic notes, as so many reporters are no longer printing to paper notes. Different brands of reporting machines create files with different naming conventions, and we want to standardize the names so someone in district administration can find the right notes easily if we are not around.
So we want to rename FILE.001, FILE.002, and 20151018-082815.sgstn, for example, to the date the file was created. The sgstn file, of course, has a unique name, but the ubiquitous writers that create FILE.* files really need renaming, and standardization will help all. I'm creating a CMD file that will also poll for the judge's name and the writer brand, so anyone pulling the notes out of storage will find exactly what they're looking for: "2015-10-18 Judge Jones, Stentura writer.001"
I've found plenty of solutions for renaming files with TODAY's date and time, but we want to rename them with THEIR OWN date and time.
I'm working as a standard user in Windows 7 Pro and do not have the option of installing third-party software. Windows allows individual users to set their preferred date style, and dbenham and others here have shown me how to get that style from the registry:
:: For REG.EXE 3.0 (Windows XP) and later versions
FOR /F "tokens=3" %%A IN (
'REG QUERY "HKCU\Control Panel\International" /v sShortDate'
) DO (SET sShortDate=%%A)
Echo %sShortDate%
That will return yyyy-MM-dd or d-M-yy or whatever the user has chosen.
And then I can test to see what the contents are of the different pieces of the string:
for /f "tokens=1,2,3 delims=/-" %%A in ("%sShortDate%") do (
for /f "tokens=1" %%D in ("%%A") do (
set Part1=%%D
)
for /f "tokens=1" %%D in ("%%B") do (
set Part2=%%D
)
for /f "tokens=1" %%D in ("%%C") do (
set Part3=%%D
)
)
echo Part1 = %Part1%
echo Part2 = %Part2%
echo Part3 = %Part3%
But this is all getting really unwieldy, and I'm only halfway there after a solid 24 hours of reading here and elsewhere. Is there really no way in Windows, at the CMD prompt or in any command-line-available tool, to get the date of a file in a predictable format and to use that date?
Can anyone take pity on me and give us a less cumbersome means of finding out what the user's particular system thinks the date should be formatted as and thus consistently rename all files that get dropped on the CMD shortcut?
Finally, this is my first post here. All constructive criticism gladly accepted. Seriously.
-- Timothy J. McGowan
Edited to add:
Maybe I've been overthinking this. It's the user's hive in the registry I'm polling for the date format. We ought to be able to write to our own hive from the command line; right?
So I could read the user's preferred date format, save that to a variable, force the date format I want to use, process the files, and then reset the user's date format. Right? Worth a shot.
I'll report back if it works, but any more comments are quite welcome!
A first idea :
Use the delimiters to get the file date or name or extension
#echo off
setlocal enabledelayedexpansion
for %%a in (*.*) do (
set "$FileName=%%~na"
set "$FileExtension=%%~xa"
set "$FileDate=%%~ta"
set "$FileDate=!$FileDate:/=-!"
echo !$FileDate!-!$FileName!!$FileExtension!)
EDIT I
To get the date in YYYY-MM-DD :
#echo off
setlocal enabledelayedexpansion
for %%a in (*.*) do (
set "$FileName=%%~na"
set "$FileExtension=%%~xa"
set "$FileDate=%%~ta"
set "$FileDate=!$FileDate:/=-!"
set "$FileDate=!$FileDate:~6,4!-!$FileDate:~3,2!-!$FileDate:~0,2!"
echo !$FileDate!-!$FileName!!$FileExtension!)
Perhaps this isn't a full answer to the question I asked, but it should be all I need to get a predictable date.
It's possible to save the user's preferred date style from the Registry, force one you want to work with, conduct your business, and then return the user's preferred date style (assuming they don't cancel the batch file in the middle of the run).
The output is messy but it simply proves the concept works.
#echo off
:: replace and then restore date style in Windows registry.
:: find current date style; save to environment variable OriginalsShortDate
FOR /F "tokens=3" %%A IN (
'REG QUERY "HKCU\Control Panel\International" /v sShortDate'
) DO SET OriginalsShortDate=%%A
:: display current date style as reflected by date of this CMD/BAT file
echo Current date style to be saved: %OriginalsShortDate%
echo Looks like this:
dir %0
echo Press any key to set yyyy-MM-dd date style
pause
:: force preferred date style and hide success message
reg add "HKCU\Control Panel\International" /v sShortDate /d yyyy-MM-dd /f >nul
:: prove it's changed
:: //////////// here's where you do your business \\\\\\\\\\\\
echo Check file's date now.
dir %0
echo (Your Windows task bar may not reflect change immediately.)
echo.
echo Press any key to set MM-dd-yy date style
pause
:: force next style
reg add "HKCU\Control Panel\International" /v sShortDate /d MM-dd-yy /f >nul
:: prove it's changed
echo Check file's date now; it will be in MM-dd-yy format.
dir %0
echo Press any key to return date format to your preferred style.
pause
:: return to user's original setting
reg add "HKCU\Control Panel\International" /v sShortDate /d %OriginalsShortDate% /f >nul
:: prove it's back to normal
dir %0
echo Your original, presumably preferred, date style has been reset.
echo Give your Windows task bar some time to update.

How to use date variables in PuTTY/PSFTP batch-script?

I like to use date variables in a PuTTY/PSFTP batch-script to select files with a certain timestamp in the filename.
But I couldn't find anything in the docs. Is there a command for PuTTY/PSFTP batch-script to use date-variables or is there a way to pass Windows Batch Variables to PSFTP?
The file looks like this: FILENAME_2015-06-25.TXT (based on the current date)
Something like this:
cd /subdir
get FILENAME_%year%-%month%-%day%.TXT
quit
In a Windows Batch File i can easily get the current date by something like this:
SET YEAR=%DATE:~-4%
SET MONTH=%DATE:~-7,2%
SET DAY=%DATE:~-10,2%
ECHO FILENAME_%YEAR%-%MONTH%-%DAY%.TXT
You have to generate the psftp script file dynamically like:
SET YEAR=%DATE:~-4%
SET MONTH=%DATE:~-7,2%
SET DAY=%DATE:~-10,2%
ECHO cd /subdir > script.txt
ECHO get FILENAME_%YEAR%-%MONTH%-%DAY%.TXT >> script.txt
psftp.exe -b script.txt ...
Though note that the %DATE% is not really a reliable approach to retrieving timestamp with a fixed format as its value changes with locale.
You can use this instead:
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set LDT=%%j
ECHO get FILENAME_%LDT:~0,4%-%LDT:~4,2%-%LDT:~6,2%.TXT >> script.txt
For details see:
How to get current datetime on Windows command line, in a suitable format for using in a filename?
Alternatively use WinSCP scripting (that supports timestamps natively) from a batch file (.bat) like:
winscp.com /log=winscp.log /command ^
"open ftp://username:password#host" ^
"cd /subdir" ^
"get FILENAME_%%TIMESTAMP#yyyy-mm-dd%%.TXT" ^
"exit"
For details see:
%TIMESTAMP% syntax
Converting PSFTP script to WinSCP script
(I'm the author of WinSCP)

Batch command date and time in file name

I am compressing files using WinZip on the command line. Since we archive on a daily basis, I am trying to add date and time to these files so that a new one is auto generated every time.
I use the following to generate a file name. Copy paste it to your command line and you should see a filename with a Date and Time component.
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip
Output
Archive_20111011_ 93609.zip
However, my issue is AM vs PM. The AM time stamp gives me time 9 (with a leading blank space) vs. 10 naturally taking up the two spaces.
I guess my issue will extend to the first nine days, first 9 months, etc. as well.
How do I fix this so that leading zeroes are included instead of leading blank spaces so I get Archive_20111011_093609.zip?
Another solution:
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
It will give you (independent of locale settings!):
20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<minutes difference to UTC> )
From here, it is easy:
set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023
For Logan's request for the same outputformat for the "date-time modified" of a file:
for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%
It is a bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes).
Extract the hour, look for a leading space, if found replace with a zero;
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip
You should search; you can simply replace all spaces with zero set hr=%hr: =0% – jeb Oct 11 '11 at 14:16
So I did:
set hr=%time:~0,2%
set hr=%hr: =0%
Then use %hr% inside whatever string you are formatting to always get a two-digit hour.
(Jeb's comment under the most popular answer worked the best for me and is the simplest. I repost it here to make it more obvious for future users.)
As Vicky already pointed out, %DATE% and %TIME% return the current date and time using the short date and time formats that are fully (endlessly) customizable.
One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.
It's a complete nightmare for a BAT programmer.
Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.
Fortunately, there is an alternative.
You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F command.
So, putting the pieces together, try this as a starting point...
SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A FD=%%F*1000000+%%D*100+%%A
SET /A FT=10000+%%B*100+%%C
SET FT=!FT:~-4!
ECHO Archive_!FD!_!FT!.zip
)
I found the best solution for me, after reading all your answers:
set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"
If AM I get 20160915_ 150101 (with a leading space and time).
If PM I get 20160915_2150101.
#For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do #(
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"
This takes MB5L.txt and compresses it to ziptest20120204.zip if run on 4 Feb 2012
You can add leading zeroes to a variable (value up to 99) like this in batch:
IF 1%Var% LSS 100 SET Var=0%Var%
So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.
However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:
HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero
(That last one controls whether there is a leading zero on times, but not dates as far as I know).
From the answer above, I have made a ready-to-use function.
Validated with french local settings.
:::::::: PROGRAM ::::::::::
call:genname "my file 1.txt"
echo "%newname%"
call:genname "my file 2.doc"
echo "%newname%"
echo.&pause&goto:eof
:::::::: FUNCTIONS :::::::::
:genname
set d1=%date:~-4,4%
set d2=%date:~-10,2%
set d3=%date:~-7,2%
set t1=%time:~0,2%
::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
set t1=%t1: =0%
set t2=%time:~3,2%
set t3=%time:~6,2%
set filename=%~1
set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
goto:eof
As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.
But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):
rem // Resolve AM/PM time:
set "HOUR=%TIME:~,2%"
if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%
Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME%, expressions).
You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:
rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.
The only way to have the same day in %CURRDATE% and %CURRTIME% is this:
rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Fix date/time midnight discrepancy:
if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.
The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.
Your question seems to be solved, but ...
I'm not sure if you take the right solution for your problem.
I suppose you try to compress each day the actual project code.
It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.
Ok, perhaps it could be that I'm wrong.
I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.
Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)
If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!
The DOS Batch command:
echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"
Prints:
Tue 04/09/2012 10:40:38.25
20120904-104038
Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.
EDIT:
A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.
So, these three lines of DOS batch:
echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%
Produce:
20120904-114434
So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:
sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log
And I'm a happy camper again (except life was still SOOOOO much easier on Unix).
I prever to use this over the current accepted answer from Stephan as it makes it possible to configure the timestamp using named parameters after that:
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
It will provide the following parameters:
Day
DayOfWeek
Hour
Milliseconds
Minute
Month
Quarter
Second
WeekInMonth
Year
You can then configure your format like so:
SET DATE=%Year%%Month%%Day%
So you want to generate date in format YYYYMMDD_hhmmss.
As %date% and %time% formats are locale dependant you might need more robust ways to get a formatted date.
Here's one option:
#if (#X)==(#Y) #end /*
#cscript //E:JScript //nologo "%~f0"
#exit /b %errorlevel%
#end*/
var todayDate = new Date();
todayDate = "" +
todayDate.getFullYear() +
("0" + (todayDate.getMonth() + 1)).slice(-2) +
("0" + todayDate.getDate()).slice(-2) +
"_" +
("0" + todayDate.getHours()).slice(-2) +
("0" + todayDate.getMinutes()).slice(-2) +
("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);
and if you save the script as jsdate.bat you can assign it as a value :
for /f %%a in ('jsdate.bat') do #set "fdate=%%a"
echo %fdate%
or directly from command prompt:
for /f %a in ('jsdate.bat') do #set "fdate=%a"
Or you can use powershell which probably is the way that requires the less code:
for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"
Adding other options to this list of answers.
you could have replaced empty space with a 0 something like echo %time: =0%
but that is still dependent, move that code to a buddy's PC in some other random place and you'll get funny outputs. So you can incorporate powershell's Get-Date:
for /f "tokens=*" %%i in ('PowerShell -Command "Get-Date -format 'yyyymmdd_HHmmss'"') do echo %%i.zip"
A space is legal in file names. If you put your path and file name in quotes, it may just fly. Here's what I'm using in a batch file:
svnadmin hotcopy "C:\SourcePath\Folder" "f:\DestPath\Folder%filename%"
It doesn't matter if there are spaces in %filename%.

How to create a folder with name as current date in batch (.bat) files

I don't know much about windows .bat file syntax. My simple requirement is to create a folder at a specific location with name as current date. I tried searching this on google but didn't get any good option. Is there any way to do this?
mkdir %date:~-4,4%%date:~-10,2%%date:~7,2%
Quick and dirty: If you can live with the date being UTC instead of local, you can use:
for /f "skip=1" %%d in ('wmic os get localdatetime') do if not defined mydate set mydate=%%d
md %mydate:~0,8%
Works in all locales. Only on XP and higher, though.
Try this (an equivalent of bash backquotes):
for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a
mkdir %datestr%
For further information, see http://ss64.com/nt/for_cmd.html
You need to get rid of the '/' characters in the date before you can use it in mkdir like this:
setlocal enableextensions
set name=%DATE:/=_%
mkdir %name%
If you want mm-dd-yyyy format you can use:
mkdir %date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
This depends on the regional settings of the computer, so first check the output of the date using the command prompt or by doing an echo of date.
To do so, create a batch file and add the below content
echo %date%
pause
It produces an output, in my case it shows Fri 05/06/2015.
Now we need to get rid of the slash (/)
For that include the below code in the batch file.
set temp=%DATE:/=%
if you echo the "temp", you can see the date without the slash in it.
Now all you need to do is formatting the date in the way you want.
For example I need the date in the format of YYYYMMDD, then I need to set the dirname as below
To explain how this works, we need to compare the value of temp
Fri 05062015.
now position each characters with numbers starting with 0.
Fri 0506201 5
01234567891011
So for the date format which I need is 20150605,
The Year 2015, in which 2 is in the 8th position, so from 8th position till 4 places, it will make 2015.
The month 06, in which 0 is in the 6th position, so from 6th position till 2 places, it will make 06.
The day 05, in which 0 is in the 4th position, so from 4th position till 2 places, it will make 05.
So finally to set up the final format, we have the below.
SET dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"
To enhance this date format with "-" or "_" in between the date, month and year , you can modify with below
SET dirname="%temp:~8,4%-%temp:~6,2%-%temp:~4,2%"
or
SET dirname="%temp:~8,4%_%temp:~6,2%_%temp:~4,2%"
So the final batch code will be
======================================================
#echo off
set temp=%DATE:/=%
set dirname="%temp:~8,4%%temp:~6,2%%temp:~4,2%"
mkdir %dirname%
======================================================
The directory will be created at the place where this batch executes.
echo var D = new Date() > tmp.js
echo D = (D.getFullYear()*100+D.getMonth()+1)*100+D.getDate() >> tmp.js
echo WScript.Echo( 'set YYYYMMDD='+D ) >> tmp.js
echo #echo off > tmp.bat
cscript //nologo tmp.js >> tmp.bat
call tmp.bat
mkdir %YYYYMMDD%
I had a problem with this because my server ABSOLUTELY had to have its date in MM/dd/yyyy format, while I wanted the directory to be in YYYY-MM-DD format for neatness sake. Here's how to get it in YYYY-MM-DD format, no matter what your regional settings are set as.
Find out what gets displayed when you use %DATE%:
From a command prompt type:
ECHO %DATE%
Mine came out 03/06/2013 (as in 6th March 2013)
Therefore, to get a directory name as 2013-03-06, code this into your batch file:
SET dirname="%date:~6,4%-%date:~0,2%-%date:~3,2%"
mkdir %dirname%
for /F “tokens=1-4 delims=/ ” %%A in (‘date /t’) do (
set DateDay=%%A
set DateMonth=%%B
set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
md %CurrentDate%
This will give you a newly created folder with today’s date, in the format of DD-MM-YY
Sourced from: Ali's Knowledge Base
This should work:
mkdir %date%
If it doesn't, try this:
setlocal enableextensions
mkdir %date%
this is a more simpler solution.
#ECHO OFF
set name=%date%
echo %name%
mkdir %name%
I am sitting in exactly the same boat as you as soon as i am AM before 10 i cannot use the below, i have set my time from 12hr to 24 hr, changed hh/mm to HH/mm I have tried most of the codes i could find. below will help at least a little. tweak and fix :)
Below may help also
set DD=%DATE:~0,2%
set MM=%DATE:~3,2%
set YY=%DATE:~8,2%
set YYYY=%DATE:~6,4%
set hh=%hh: =0%
set mm=%TIME:~3,2%
if "%time:~0,1%" == " " (set folderdate=0%time:~1,1%) ELSE set folderdate=%time:~0,2%
mkdir folderdate=%date:~6%%date:~3,2%%date:~0,2%_%folderdate%%time:~3,2%
copy \Makereport*.CSV \Makereport\%folderdate%\
cd %folderdate%
REM -( 7zip in c:\batch)
Path = c:\batch
7z a Retail.zip *.CSV -pRetailPassword
cd..
del *.csv
the expression %date:~p,n% returns n number of characters from position p in the date string.
if my system date string is Mon23/11/2015
the command
%date:~1,3%
returns the value
Mon
the command
%date:~10,4%
returns the value
2015
and in conjunction with the md (or mkdir) command
the command
md %date:~10,4%%date:~7,2%%date:~4,2%
makes a directory named
20151123
likewise if your date string in in the format
Monday, 23/Nov/2015
the command
md %date:~16,4%%date:~12,3%%date:~9,2%
makes a directory named
2015Nov23
If you accidentally return characters from the date string that are not allowed in folder names or use invalid values for p and n you will get an error.
Additionally if you return values that include \ this may create a folder within a folder.
If your locale has date format "DDMMYYYY" you'll have to set it this way:
set datestr=%date:~-4,4%%date:~3,2%%date:~-10,2%
mkdir %datestr%
This works for me, try:
ECHO %DATE:~7,2%_%DATE:~4,2%_%DATE:~12,2%
Thanks for the info all, very helpful. I needed something that could create "backup" folder as often as every minute in the same directory, as well as call on it later in the script. Here's what I came up with:
# echo off
CD %userprofile%\desktop
SET Datefolder="%DATE:~4,2%-%DATE:~7,2%-%DATE:~12,2%_%time:~1,1%%time:~3,2%"
MD "%Datefolder%"
This gives me a folder on the currently logged on user's desktop named: mm-dd-yy_hmm (hour minute minute) ie: 07-28-15_719
You'll like this, change it so that it can suit your requirements.
mkdir today
Copy Desktop\test1\*.* today
setlocal enableextensions
set name=%DATE:/=_%
Rename "today" _OlddatabaseBackup_"%name%"
Use this batch script made by me:
#echo off
title Folder Creator
color b
setlocal enabledelayedexpansion
echo Enter the folder name, you can use these codes:
echo /t - Time (eg. 16:29)
echo /d - Date (eg. 17-02-19)
echo /a - Day (eg. 17)
echo /m - Month (eg. 02)
echo /y - Year (eg. 19)
echo /f - Full Year (eg. 2019)
echo.
set /p foldername=Folder Name:
set foldername=%foldername:/t=!time:~0,5!%
set foldername=%foldername:/d=!date:~0,2!-!date:~3,2!-!date:~8,2!%
set foldername=%foldername:/a=!date:~0,2!%
set foldername=%foldername:/m=!date:~3,2!%
set foldername=%foldername:/y=!date:~8,2!%
set foldername=%foldername:/f=!date:~6,4!%
md %foldername%
For example if you wanted to make a folder named the date in the DD-MM-YY format you would type "/d" but if you wanted to do that in the DD-MM-YYYY format you would type "/a-/m-/f".
I use the next code to make a file copy (e.g. test.txt) before replacing:
cd /d %~dp0
set backupDir=%date:~7,2%-%date:~-10,2%-%date:~-2,2%_%time:~0,2%.%time:~3,2%.%time:~6,2%
echo make dir %backupDir% ...
md "%backupDir%"
copy test.txt %backupDir%
It creates directory in format DD-MM-YY_HH.MM.SS and places text.txt there.
Time with seconds in the name is necessary to create directory without additional verification.
https://stackoverflow.com/a/31789045/1010918 foxidrive's answer helped me get the folder with the date and time I wanted. I would like to share this method here since it worked great for me and I think it could help other people too, regardless of their locale.
rem The four lines below will give you reliable YY DD MM YYYY HH Min Sec MS variables in XP Pro and higher.
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"
set "dirname=%YYYY%-%MM%-%DD% %HH%-%Min%-%Sec%"
:: remove echo here if you like
echo "dirName"="%dirName%"
this worked better for me,
#echo off
set temp=%DATE:/=%
set dirname="%temp:~4,4%%temp:~2,2%%temp:~0,2%"
mkdir %dirname%
For YYYY.MM.DD format with HUN settings use following. It converts "2021. 02. 23." to "2021.02.23":
SET dirname="%date:~0,5%%date:~6,3%%date:~10,2%"
md %dirname%
G:
cd G:/app/
mkdir %date:~7,2%%date:~-10,2%%date:~-4,4%
cd %date:~7,2%%date:~-10,2%%date:~-4,4%
sqlplus sys/sys as sysdba #c:/new
I needed both the date and time and used:
mkdir %date%-%time:~0,2%.%time:~3,2%.%time:~6,2%
Which created a folder that looked like:
2018-10-23-17.18.34
The time had to be concatenated because it contained : which is not allowed on Windows.
setlocal enableextensions
set name="%DATE:/=_%"
mkdir %name%
to create only one folder like "Tue 01_28_2020"

Resources