由於對接zabbix監控的需要,需要監控指定目錄下文件數量是否超標、文件總大小是否超標,爲此需要寫個腳本獲取:
- 指定目錄或指定文件的文件數量,如指定文件則返回1
- 指定目錄或指定文件的文件磁盤佔用空間
Bat/cmd腳本實現原理如下:
dir /s 目錄或文件
2020/03/08 17:49 139 file_size.tmp
2020/03/08 17:48 733 file_statics.bat
2020/03/07 10:48 26 md5_tst.txt
2020/03/07 10:48 49 md5_tst.txt.md5
7 個文件 1,784 字節
所列文件總數:
7 個文件 1,784 字節
2 個目錄 88,523,546,624 可用字節
解析最後2行:文件數量、文件大小即可,具體代碼如下:
1、file_size.bat
@echo off & setlocal enabledelayedexpansion
rem 參數去引號
set arg1=%~1
set arg2=%~2
rem 第一個參數必須是size或count
if "%arg1%" == "size" goto file_statics
if "%arg1%" == "count" goto file_statics
goto usage
:file_statics
rem 指定目錄或文件路徑不能爲空
if "%arg2%" == "" goto usage
if not exist %arg2% goto usage
rem 利用dir /s 統計文件數量、大小,輸出到file_size.tmp
dir /s %arg2% | find "字節" > file_size.tmp
rem 解析file_size.tmp得到文件數量、大小
set total=0
for /f %%i in (file_size.tmp) do (
set /a total+=1
)
set /a total=%total%-1
set count=0
for /f "tokens=1,2,3,*" %%i in (file_size.tmp) do (
set /a count+=1
if !count! equ %total% (
set file_count=%%i
set file_size=%%k
)
)
if "%arg1%" == "count" echo %file_count:,=%
if "%arg1%" == "size" echo %file_size:,=%
goto :eof
:usage
echo "%0 size|count filepath|folderpath"
exit /b 1
2、用法演示
D:\bat_cmd>file_statics.bat count d:\bat_cmd
7
D:\bat_cmd>file_statics.bat size d:\bat_cmd
1645
D:\bat_cmd>file_statics.bat size d:\bat_cmd\file_statics.bat
733
D:\bat_cmd>file_statics.bat count d:\bat_cmd\file_statics.bat
1
3、注意事項
由於腳本file_size.bat中有中文,文件保存時請注意編碼格式,vscode請用gb2312.