BAT批处理脚本案例--获取指定目录下文件数量、文件占用磁盘空间大小

由于对接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.

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值