一、介绍bat批处理文件之前先了解下基本批处理代码
1.::
添加注释。
2.set
设置变量。
3.echo
内容输出,输出字符串常量不需要加引号、双引号,输出变量时,变量两边需要加英文感叹号!
,如!NowYM!
。
4.delims
切割函数,《for /f命令之—Delims和Tokens用法&总结》介绍很详细,可供参考。
5.%date:~0,4%
获取年份,date表示当前时间,0,4表示从位开始截取,截取到第四位,具体见脚本。
二、bat脚本
当前脚本功能主要实现了
将bat脚本所在目录下所有修改日期为今天的文件(注意这里是文件,不包含文件夹)复制到today文件夹下,重复执行bat时,存在重名文件不会询问直接替换
,脚本解析可见::
后注释。
::设置关闭批处理回显、设置cmd标题
@echo off & title Copy the file according to the modification date
cd /d %~dp0
setlocal enabledelayedexpansion
::获取当前时间NowDate,格式为20211202样式
set NowDate=%date:~,4%%date:~5,2%%date:~8,2%
::echo输出语句
echo 复制修改日期为!NowDate!的文件
::判断是否存在today文件夹,找不到则新建
if not exist today md today
::delims切割函数,'dir /a-d /b /tw'表示for循环遍历当前目录下的文件
for /f "delims=" %%a in ('dir /a-d /b /tw') do (
::这行没看懂i
if not "%%~fa"=="%~f0" (
::%%~ta获取日期/时间
set FileDate=%%~ta
::格式化FileDate为上面NowDate同样式
set FileDate=!FileDate:~,4!!FileDate:~5,2!!FileDate:~8,2!
::拿格式化后文件修改时间和当前时间作比较,相同则复制文件到today文件夹下。
if !FileDate! equ !NowDate! copy "%%~a" today\
)
)
::关闭cmd窗口,想查看输出结果可以将exit改pause,cmd窗口将不进行关闭操作。
exit
三、懒人必备
比如自己桌面每天新建很多文件很乱,想要将桌面当天的文件定时以时间戳为文件名创建文件夹并把文件
移动
到改文件夹下,可以参考下面写好的bat,再配置到windows系统自带的任务计划程序
中去定时执行,简直了,配置如图。
脚本如下,但是脚本只能放到桌面,放到其他路径需要修改for循环中('dir /a-d /b /tw')
模块遍历路径,但由于本小白暂未找到书写方式,欢迎大佬们前来指点一二。
@echo off & title Copy the file according to the modification date
cd /d %~dp0
setlocal enabledelayedexpansion
set NowDate=%date:~,4%%date:~5,2%%date:~8,2%
if not exist !NowDate! md !NowDate!
for /f "delims=" %%a in ('dir /a-d /b /tw') do (
if not "%%~fa"=="%~f0" (
set FileDate=%%~ta
set FileDate=!FileDate:~,4!!FileDate:~5,2!!FileDate:~8,2!
if !FileDate! equ !NowDate! move "%%~a" !NowDate!\
)
)
exit