如何使用批处理(Batch)批量创建带周序号与递增日期的文件夹(持续6个月)
Can I create weekly folders for 6 months with a Batch script?
Absolutely! You can automate this task completely with a Windows Batch script. The key challenge here is reliably calculating weekly dates (handling months with different days, leap years, etc.), so we’ll pair Batch with PowerShell for date arithmetic—since PowerShell has built-in, robust date handling that avoids the headaches of manual date calculations in pure Batch.
Here’s a ready-to-use script that does exactly what you need:
@echo off setlocal enabledelayedexpansion :: Configure your starting settings set "startDate=2021-09-09" set "currentWeek=1" :: Calculate the end date (6 months after the start date) for /f %%a in ('powershell -Command "(Get-Date '%startDate%').AddMonths(6).ToString('yyyy-MM-dd')"') do set "endDate=%%a" set "currentDate=%startDate%" :folderLoop :: Format the current date to dd-MM-yyyy for folder naming for /f %%b in ('powershell -Command "(Get-Date '%currentDate%').ToString('dd-MM-yyyy')"') do set "formattedDate=%%b" :: Create the folder with the week number and date mkdir "W!currentWeek! !formattedDate!" :: Calculate the next week's date (add 7 days) for /f %%c in ('powershell -Command "(Get-Date '%currentDate%').AddDays(7).ToString('yyyy-MM-dd')"') do set "currentDate=%%c" :: Increment the week counter set /a currentWeek+=1 :: Check if we've passed the 6-month mark for /f %%d in ('powershell -Command "if ((Get-Date '%currentDate%') -gt (Get-Date '%endDate%')) {echo 1} else {echo 0}"') do set "isFinished=%%d" if !isFinished! equ 1 goto :cleanup goto :folderLoop :cleanup echo All weekly folders created successfully! endlocal
How this works:
- Initial setup: We define your starting date (
startDate) and initial week number (currentWeek). The end date is automatically calculated as 6 months after the start date using PowerShell. - Loop logic: For each iteration:
- We format the current date to match your desired
dd-MM-yyyyformat. - We create a folder named like
W1 09-09-2021,W2 16-09-2021, etc. - We add 7 days to the current date to get the next week's date.
- We increment the week number.
- We check if we’ve exceeded the 6-month end date—if yes, we exit the loop.
- We format the current date to match your desired
Notes:
- This script works on Windows 7 and later (all modern Windows versions include PowerShell by default).
- To change the starting date or duration, just modify the
startDatevalue or adjustAddMonths(6)to another number (e.g.,AddMonths(3)for 3 months). - Run the script from the directory where you want the folders created, or add a
cd "C:\Your\Target\Directory"line at the top to specify a location.
内容的提问来源于stack exchange,提问作者Pierre Auger
相关产品推荐
相关产品推荐

