windows系統內建一個命令forfiles可以根據檔案的時間戳記來操作檔案,
forfiles /? 可以查看詳細的協助
FORFILES [/P pathname] [/M searchmask] [/S] [/C command] [/D [+ | -] {yyyy/MM/dd | dd}]
/p “目錄名” 指定搜尋路徑
/S 遞迴搜尋
/C “指定要執行的命令”
/D 指定時間尋找
+ yyyy/MM/dd 指定絕對時間,尋找並這個日期晚的檔案
– dd 相對目前時間,併當前時間早n天的檔案
顯示指定目錄下超過6天沒修改的檔案,預設會輸出檔案名
forfiles /p “%bak_dir%” /S /D -6
forfiles /p “%bak_dir%” /S /D -6 -C “cmd /c echo @file”
輸出完整路徑
forfiles /p “%bak_dir%” /S /D -6 -C “cmd /c echo @path”
刪除指定目錄下最後修改時間超過6天的檔案
forfiles /p “%bak_dir%” /S /D -6 /C “cmd /c del /q @file”
備份指定路徑下的檔案,先設定環境變數,由於不內使用兩次””所以無法使用變數替換的方式引用rar.exe
IF EXIST “c:\Program Files\winrar” set Path=;”c:\Program Files\winrar”;%SystemRoot%\system32
IF EXIST “c:\Program Files (x86)\winrar” set Path=;”c:\Program Files (x86)\winrar”;%SystemRoot%\system32
forfiles /p “%bak_dir%” /S /D -6 /C “cmd /c rar.exe a backp.rar @path”
bat擷取上個月份
@echo off
setlocal EnableDelayedExpansion
pause
rem ################# 獲得上個月的日期 ########################
rem 擷取年度
set year=%date:~0,4%
rem 擷取月份
echo 當前年份: %year%
set mounth=%date:~5,2%
echo 當前月份: %mounth%
echo #####################
if "%mounth%"=="01" (
set /A year=%year%-1
set /A lastmounth=01
echo 當前年月: %year%_%mounth%
echo **************
) else (
rem 將當前月份減一
echo %mounth%
set /A lastmounth=!mounth!-1
echo 上個月份: !lastmounth!
rem 如果當前月份減1後,小於10 則 用零補充 例如 2 = 02
if !lastmounth! lss 10 (
set lastmounth=!lastmounth!
)
echo 上個月: %year%_!lastmounth!
)
pause
方法二
?
@echo off
rem setlocal
echo 日期:%date%
REM 分離年月日
@set year=%date:~0,4%
set month=%date:~5,2%
set day=%date:~8,2%
echo this year: %year%
echo this month: %month%
echo ############# test #################
if "%month%"=="01" (
set /A lastyear=%year%-1
echo last year: %lastyear%
set lastmonth=12
echo last month: %lastmonth%
echo last year_month: %lastyear%_%lastmonth%
echo ############ month == 01 #############
)else (
if "%month%"=="02" set lastmonth=01
if "%month%"=="03" set lastmonth=02
if "%month%"=="04" set lastmonth=03
if "%month%"=="05" set lastmonth=04
if "%month%"=="06" set lastmonth=05
if "%month%"=="07" set lastmonth=06
if "%month%"=="08" set lastmonth=07
if "%month%"=="09" set lastmonth=08
if "%month%"=="10" set lastmonth=09
if "%month%"=="11" set lastmonth=10
if "%month%"=="12" set lastmonth=11
echo last year_month: %year%_%lastmonth%
echo ############### month != 01 ##############
)
pause