Reputation: 11
I'm trying to use a batch script to create a folder and a subfolder with dates.
What I want is to create a folder in the directory as November 2018
and inside it another folder called 27-11-2018
.
What I have tried so far is:
@echo off
set day=%Date:~0,2%
set month=%Date:~3,2%
set year=%Date:~6,4%
echo %day%
echo %month%
echo %year%
if %month%==11 set month-name=November
pause
set folder="%month-name% %year%\%day%-%month%-%year%"
echo %folder%
md %folder%
pause
The output is:
27
11
2018
Press any key to continue . . .
"November 2018\27-11-2018"
The system cannot find the path specified.
Press any key to continue . . .
The echoed line is correct and the November 2018
folder is created, but not the subfolder.
What I've tried is to create just November 2018
folder and this works, but obviously, this, doesn't create subfolder.
I've also replaced the space with underscore as per below and this works, too so it seems like its the space causing the issue.
set folder="%month-name%_%year%\%day%-%month%-%year%"
Any ideas? I am sure there has got to be an easy answer to this.
Upvotes: 1
Views: 1655
Reputation:
For mkdir to create nested folders in one go you need extensions to be enabled (should be default), otherwise use setlocal EnableExtensions
.
I suggest not to use the %date% variable which is locale/user settings dependent. Use either wmic or PowerShell for this.
Also create a MonthName array and use the month as an index to select current month.
:: Q:\Test\2018\11\27\SO_53497757.cmd
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
:: Build MonthName[01..12] array
Set i=100&Set "MonthName= January February March April May June July August September October November December"
Set "MonthName=%MonthName: ="&Set /a i+=1&Set "MonthName[!i:~-2!]=%"
:: Set MonthName
:: get datetime independent of locale/user settings.
for /f "tokens=1-3 delims=.+-" %%A in (
'wmic os get LocalDateTime^|findstr ^^[0-9]'
) do Set _IsoDT=%%A
Set "yy=%_IsoDT:~0,4%"&Set "MM=%_IsoDT:~4,2%"&Set "dd=%_IsoDT:~6,2%"
set "folder=!MonthName[%MM%]! %yy%\%dd%-%MM%-%yy%"
echo %folder%
md "%folder%"
EDIT: alternatively use a PowerShell one liner wrapped in batch
powershell -NoP -C "md (get-date).ToString('MMMM yyyy\\dd-MM-yyyy')"
Upvotes: 1
Reputation: 314
Do not create both dir and subdir in one go. First create dir then create subdir in it.
set folder="%month-name% %year%"
echo %folder%
md %folder%
cd %folder%
set folder="%day%-%month%-%year%"
echo %folder%
md %folder%
Upvotes: 0