由于对接zabbix监控的需要,需要监控指定目录下文件数量是否超标、文件总大小是否超标,为此需要写个脚本获取:
- 指定目录或指定文件的文件数量,如指定文件则返回1
- 指定目录或指定文件的文件磁盘占用空间
Bat/cmd脚本实现原理如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12dir /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
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41@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、用法演示
复制代码
1
2
3
4
5
6
7
8
9
10
11
12D: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_cmdfile_statics.bat 733 D:bat_cmd>file_statics.bat count d:bat_cmdfile_statics.bat 1
3、注意事项
由于脚本file_size.bat中有中文,文件保存时请注意编码格式,vscode请用gb2312.
最后
以上就是清脆纸飞机最近收集整理的关于BAT批处理脚本案例--获取指定目录下文件数量、文件占用磁盘空间大小的全部内容,更多相关BAT批处理脚本案例--获取指定目录下文件数量、文件占用磁盘空间大小内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复