How can we use a command to get exact size of files or folders in CMD?

69 Views Asked by At

I know nothing about bat file or cmd file. I asked chatGPT to pull me someting that I can use as command as such:

fsize <filename[s]>

where fsize takes filename[s] and calculate size in human readable format. fsize.cmd:

@echo off
setlocal enabledelayedexpansion

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

    REM Check if the file or folder exists
    if not exist "!filename!" (
        echo !filename! does not exist
    ) else (
        REM Determine if it's a file or folder
        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 { Write-Output '!filename! = '($size / 1GB) GB } }"
            )
        ) else if /i !type! equ folder (
            echo !filename! is a folder
        )
    )
)

I test it and it is working quite fine. Well I wanna solve couple of issues of this fsize.cmd which are: Before addressing issue I would like to show results of dir /b command :

file.txt
fsize.cmd
hell

where hell is folder

Issue 1: when I asked fsize to render size of file.txt as: fsize file.txt results:

file.txt = 
1.44921875
KB 

The results are in 3 lines which is untidy. I expect the results to be in one line:
file.txt = 1.44921875 KB

Issue 2: if i do fsize hell it results:
hell is a folder
but when i do fsize *

file.txt = 
1.44921875
KB
fsize.cmd = 
1013 
bytes

It does not echo hell is a folder why?

Solution I want:

  1. Solve Issue 1
  2. I will appreciate anyone helping me modify the fsize.cmd in such a way that:
    fsize <filename[s]|foldername[s]>
    should render size of provided file/folders in readable format. Saying readable format I mean if size goes 1024B it should convert into KB and as such....
  3. fsize * should enounter folders too.

I get that cmd file with the help of chatGPT. This is acknowledgeable anyone saying ask GPT but it is only testing my patience and hence I can not work on these at my own I am posting this.

0

There are 0 best solutions below