【问题标题】:Batch Script in Windows Server 2008 R2Windows Server 2008 R2 中的批处理脚本
【发布时间】:2015-06-05 05:23:52
【问题描述】:

我需要一个检查文件夹大小的批处理脚本。如果它达到一些 X GB,例如:10 GB,它应该去删除其中的所有子目录或文件。

我知道这在 Linux 中会很简单。但是我对windows服务器和编写批处理脚本比较陌生。

目前我正在运行一个脚本,每次运行时都会删除文件/文件夹,类似这样

set folder="C:\myfolder"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)

但我只想在文件/文件夹达到一定 GB 大小(例如 10 或 12 GB)时删除文件/文件夹。

【问题讨论】:

  • 您的第一条语句(简而言之:删除文件夹)与最后一条仅删除文件相矛盾。
  • 感谢指正,我已经修改了。
  • 在 StackOverflow 中搜索 batch folder size 会得到 200 多个已回答的结果...
  • 为什么不安装 cygwin 并使用与 Linux 相同的命令?或者使用更现代的东西,比如已经安装或可以轻松安装的 wsh 或 powershell?

标签: windows batch-file


【解决方案1】:

在 Windows 服务器上使用 powershell。然后查找文件夹的大小:

$size = (Get-ChildItem $FolderName -Recurse | Measure-Object -Property Length -Sum).Sum
if ($size > $Limit) {
    Remove-Item $FolderName -Recurse -Whatif
}

对于为什么 powershell 可能比一组 unix 工具更有用作为Is PowerShell ready to replace my Cygwin shell on Windows? 的最佳答案,有一个很好的解释

-Whatif 使Remove-Item 安全,因为添加 -WhatIf 只报告命令在执行时会做什么。

【讨论】:

    【解决方案2】:

    对于批处理解决方案

    @echo off
        setlocal enableextensions disabledelayedexpansion
        rem      12345678901234567890
        set "pad=                    "
    
        for %%a in ("%~f1.") do set "target=%%~fa"
    
        set "limit=%~2"
        if not defined limit set "limit=10737418240"
    
        echo(Searching in [%target%] ....
    
        for /f "tokens=3" %%a in ('
            dir /s /-c /a "%target%"
            ^| findstr /i /r /c:"^  .*bytes$" 
        ') do set "size=%%a"
    
        set "limit=%pad%%limit%"
        set "size=%pad%%size%"
    
        echo(
        echo(.... limit [%limit:~-20%]
        echo(.... size  [%size:~-20%]
        echo(
    
        if "%size:~-20%" lss "%limit:~-20%" (
            echo Size is in range
            goto :eof
        )
    
        echo(Size is out of range. Cleaning ....
        pushd "%target%" && (
            rem rmdir . /s /q
            popd
        )
    

    此批处理文件使用两个参数:第一个是要处理的文件夹(默认为当前文件夹),第二个是要检查的大小限制(默认为 10GB)。

    dir 命令用于检索指定文件夹下的完整大小。使用 for /f 解析此命令的输出以获取所需的数据。

    批处理文件算法的最大值限制为 2^31。要在条件中处理更大的值,需要将数字转换为填充字符串进行比较。

    脚本仅将信息回显到控制台。您需要取消注释应该删除目标文件夹内容的 rmdir 命令。

    【讨论】:

      【解决方案3】:
      On Error Resume Next
      Set fso = CreateObject("Scripting.FileSystemObject")
      
      'make a new folder to delete
      Set f = fso.CreateFolder("c:\New Folder")
      
      'wait 30 secs to you can see it in explorer
      wscript.sleep 30000
      
      'Checking size
      Set fldr = fso.GetFolder("c:\new folder")
      Msgbox fldr.size
      
      If fldr.size > 100000000000 then msgbox "too large"
      
      fldr.delete
      

      VBScript 就是为此而设计的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多