使用.bat创建昨天的日期文件夹yyyy-mm-dd

时间:2016-03-03 11:16:52

标签: date batch-file

我正在尝试使用以下脚本创建先前日期文件夹,问题是它会跳过月份。为了说明我的观点,它最终以2016-2-结束。因此,任何有关这方面的相关反馈都将受到赞赏。

Ps:我机器的当前日期:3/3/2016

最佳,

@echo off
setlocal enabledelayedexpansion
cls
set vbs=%temp%\vbs.vbs
> %vbs% echo WScript.Echo DateAdd("d",-1,Date)
for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do (
set newfold=%%a
)
del %vbs%
for /f "tokens=1-3* delims=/ " %%1 in ("%newfold%") do (
set month=%%2&set date=%%3&set year=%%4
md !date!-!month!-!year!
echo New folder created = !date!-!month!-!year!      
)
使用VBScript函数

编辑 Weekday()

@echo off
setlocal EnableDelayedExpansion
cls
set vbs=%temp%\vbs.vbs
>%vbs% echo dateYesterday=DateAdd("d",-1,Date): 
wdayYesterday=Weekday(dateYesterday): 
If wdayYesterday=1 Then WScript.Echo DateAdd("d",-2,dateYesterday) 
Else If wdayYesterday=7 Then WScript.Echo DateAdd("d",-1,dateYesterday)
Else WScript.Echo dateYesterday
for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do (
set newfold=%%a
)
echo dateYesterday = %newfold%  ^(assumption: month/day/year^)
del %vbs%
for /f "tokens=1-3 delims=/ " %%1 in ("%newfold%") do (
set month=%%2
set day=%%1
set year=%%3
)
md %day%-%month%-%year%
echo New folder created = %day%-%month%-%year%  ^(day/month/year^)

1 个答案:

答案 0 :(得分:1)

您在第二个for /f循环中混淆了令牌:假设您的日期格式为月/日/年,则需要更改set命令行。这是更正后的代码:

@echo off
setlocal EnableDelayedExpansion
cls
set vbs=%temp%\vbs.vbs
> %vbs% echo WScript.Echo DateAdd("d",-1,Date)
for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do (
    set newfold=%%a
)
echo Yesterday = %newfold%  ^(assumption: month/day/year^)
del %vbs%
for /f "tokens=1-3 delims=/ " %%1 in ("%newfold%") do (
    set month=%%2
    set day=%%1
    set year=%%3
)
md %day%-%month%-%year%
echo New folder created = %day%-%month%-%year%  ^(day/month/year^)

由于第二个for /f循环仅迭代一次(与第一个循环一样),我将所有命令移到了set之外,因此不再需要延迟扩展。

如果你想要上一个工作日的日期(所以星期六和星期日不计算在内)你的问题的编辑,你可以只扩展临时VBScript:

@echo off
setlocal EnableDelayedExpansion
cls
set vbs=%temp%\vbs.vbs
> %vbs% echo dateYesterday=DateAdd("d",-1,Date): wdayYesterday=Weekday(dateYesterday): If wdayYesterday=1 Then WScript.Echo DateAdd("d",-2,dateYesterday) Else If wdayYesterday=7 Then WScript.Echo DateAdd("d",-1,dateYesterday) Else WScript.Echo dateYesterday
for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do (
    set newfold=%%a
)
echo Yesterday = %newfold%  ^(assumption: month/day/year^)
del %vbs%
for /f "tokens=1-3 delims=/ " %%1 in ("%newfold%") do (
    set month=%%2
    set day=%%1
    set year=%%3
)
md %day%-%month%-%year%
echo New folder created = %day%-%month%-%year%  ^(day/month/year^)

此方法使用Weekday()函数(在*.vbs脚本中)获取当周的当天(1为星期日,2为星期一,... ,7是星期六)。