###### tags: `Batch`, `.bat`, `工作排程器`
# 定期刪除檔案
這篇文章會寫一個刪除檔案的`Batch檔`並使用`Windows工作排程器`設定排程執行該Batch檔來達成定期刪除檔案的範例。
## 刪除檔案Batch檔範例
1. 若你只想刪除指定資料夾下的檔案:
```bash=
@echo off
setlocal enabledelayedexpansion
set today=%date:~0,4%%date:~5,2%%date:~8,2%
for /f "delims=" %%i in ('dir /b /a-d "YourDirectoryPath\*"') do (
set fp=YourDirectoryPath\%%i
for %%f in (!fp!) do (
set file_date=%%~tf
echo The modification time of file %%i is !file_date!
set file_date=!file_date:~0,4!!file_date:~5,2!!file_date:~8,2!
if !file_date! neq %today% (
del "YourDirectoryPath\%%i"
echo deleted %%i
)
)
)
pause
```
> 行1. `@echo off`:關閉每行的Echo(預設是每行執行時都會有輸出)。
> 行2. `setlocal enabledelayedexpansion`:允許在執行時期(runtime)對變數進行延遲擴展(delayed expansion),講白話就是可以在程式執行過程中改變變數的值。
> 行3. `%date:~index,length%`:取得日期的年月日部分。
> 行4. `/f`:找檔案,`"delims="`:取消分割符(設分割符為空), `%%i`:for迴圈迭代的變數,`dir`:列出資料夾下的內容,`/b`:只要列出檔案名稱,`/a-d`:只列出檔案,不列出資料夾。
> 行5. 將完整檔案路徑存到`fp`變數。
> 行6. 使用for迴圈取得檔案資訊,`%%f`:for迴圈迭代的變數,這邊使用`!fp!`是因為這個變數是在程是執行時(runtime)改變的,也就是第2點提到的延遲擴展。
> 行7. `%%~tf`取得檔案最後修改時間。
> 行8. 印出檔案最後修改時間。
> 行9. 取得檔案最後修改時間的年月日部分。
> 行10. 判斷跟第3點取得的今日年月日一不一樣。
> 行11. 不一樣的話就刪除該檔案。
> 行12. 印出被刪除的檔案的檔名。
> 行16. 讓Console暫停,通常是為了可以看到輸出結果。
2. 若你想遍歷該資料夾下的所有檔案與子資料夾中的檔案:
```bash=
@echo off
setlocal enabledelayedexpansion
set today=%date:~0,4%%date:~5,2%%date:~8,2%
for /r "YourDirectoryPath" %%i in (*) do (
if not "%%~ti" == "" (
set file_date=%%~ti
echo The modification time of file %%i is !file_date!
set file_date=!file_date:~0,4!!file_date:~5,2!!file_date:~8,2!
if !file_date! neq %today% (
del "%%i"
echo deleted %%i
)
)
)
pause
```
## 設定工作排程
工作排程可以使用兩種方式新增,下面我會依序實作:
1. Windows的工作排程管理器
2. Batch檔
### 使用Windows的工作排程管理器新增排程
1. 搜尋並開啟`工作排程器`。
2. 點擊`建立工作`。

4. 填入`工作名稱`、`安全性選項`。

4. 到`觸發程序`中`新增`一個排程。

5. 到`動作`中`新增`一個動作去執行你的batch檔。

### 使用Batch檔新增排程
```bash=
@echo off
set taskname="DailyDeleteOldFiles"
set command="YOURPATH\DeleteOldFiles.bat"
set starttime="04:00"
set frequency="DAILY"
schtasks /create /tn %taskname% /tr %command% /sc %frequency% /st %starttime% /f
pause
```
## 參考連結
* [ChatGPT](https://chat.openai.com/)
* [[MIS]如何設定工作排程執行.bat檔案(執行.exe檔案)](https://dotblogs.com.tw/kevinya/2015/10/26/153689)