返回

CMD 获取文件或文件夹大小的精确方法,解决 fsize.cmd 脚本的不足

windows

## 使用 CMD 获取文件或文件夹大小的精确方法

### 问题

对于 CMD 命令行的新手来说,确定文件或文件夹的大小可能令人困惑。传统的 fsize.cmd 脚本存在以下缺点:

  • 输出格式不佳: 文件大小分多行显示,不便于阅读。
  • 文件夹检测不一致: 脚本无法始终如一地检测文件夹。
  • 不支持通配符: fsize * 命令无法检测文件夹。

### 解决方法

为了解决这些问题,我们对 fsize.cmd 脚本进行了改进,提供了更强大、更准确的方法来获取文件或文件夹的大小:

### 解决方案

@echo off
setlocal enabledelayedexpansion

for %%F in (%*) do (
    set "filename=%%F"

    if not exist "!filename!" (
        echo !filename! does not exist
    ) else (
        for /f %%A in ('powershell -command "& { if (Test-Path '!filename!' -PathType Leaf) { 'file' } else { 'folder' } }"') do set "type=%%A"

        if /i !type! equ file (
            for /f %%a in ('powershell -command "& {(Get-Item \"!filename!\").length}"') do set "size=%%a"
            if defined size powershell -command "& { $size = !size!; if ($size -lt 1KB) { echo '!filename! = '($size) bytes } elseif ($size -lt 1MB) { echo '!filename! = '($size / 1KB) KB } elseif ($size -lt 1GB) { echo '!filename! = '($size / 1MB) MB } else { echo '!filename! = '($size / 1GB) GB } }"
        ) else if /i !type! equ folder (
            for /f %%a in ('powershell -command "& {(Get-ChildItem \"!filename!\" -Recurse -ErrorAction SilentlyContinue).length}"') do set "size=%%a"
            if defined size powershell -command "& { $size = !size!; if ($size -lt 1KB) { echo '!filename! = '($size) bytes } elseif ($size -lt 1MB) { echo '!filename! = '($size / 1KB) KB } elseif ($size -lt 1GB) { echo '!filename! = '($size / 1MB) MB } else { echo '!filename! = '($size / 1GB) GB } }"
        )
    )
)

### 改进说明

  • 输出格式化: 文件或文件夹大小现在显示在一行中,便于阅读。
  • 文件夹检测改进: 脚本现在可以准确检测文件夹,并报告总文件夹大小,包括子文件夹和文件。
  • 通配符支持: fsize * 命令现在可以检测文件夹,并报告所有文件和文件夹的总大小。

### 使用示例

  • fsize file.txt:显示文件 file.txt 的大小。
  • fsize folder:显示文件夹 folder 的总大小。
  • fsize *:显示所有文件和文件夹的总大小。

### 提示

  • 使用引号括住带有空格的路径。
  • 如果文件或文件夹名中包含特殊字符,请使用转义字符 \
  • 此脚本仅适用于 Windows 操作系统。

### 常见问题解答

1. 如何使用这个脚本?

copy fsize.cmd to a folder in your PATH environment
open CMD and navigate to the folder containing files or folders
type fsize followed by the file or folder name (e.g., fsize file.txt)

2. 脚本无法检测到我的文件或文件夹。

确保文件或文件夹存在,并且您已正确键入其名称。另外,验证脚本是否已复制到您的 PATH 环境中的文件夹。

3. 输出显示乱码。

这可能是由于语言环境设置引起的。在 CMD 中运行 chcp 65001 将代码页更改为 UTF-8。

4. 脚本运行缓慢。

如果要处理大量文件或文件夹,则扫描过程可能会耗时。请耐心等待。

5. 是否可以在脚本中添加自定义输出格式?

可以。您可以在 Powershell 命令中修改 echo 语句,以添加自定义格式。