Размер папки в командной строке windows

I want to use the Windows command line to calculate the size of all the files in a folder and subfolder. I would normally do this by right-clicking on the folder and clicking "Properties" but I wan...

I realize this question asked for file size analysis using CMD line. But if you are open to using PowerQuery (Excel add-in, versions 2010+) then you can create some pretty compelling file size analysis.

The script below can be pasted into a Blank Query; The only thing you’ll need to do is add a parameter named «paramRootFolderSearch» then add your value, such as «C:Usersbl0040Dropbox». I used this as a guide: MSSQLTips: Retrieve file sizes from the file system using Power Query.

This query provided the data for me to create a pivot table ([Folder Root]> [Folder Parent (1-2)], [Name]), and I was able to identify a few files that I could deleted which cleared up a lot of space in my directory.

Here is the M script for PowerQuery:

let
// Parmameters:
    valueRootFolderSearch = paramRootFolderSearch,
    lenRootFolderSearch = Text.Length(paramRootFolderSearch),
//

    Source = Folder.Files(paramRootFolderSearch),
    #"Removed Other Columns" = Table.RenameColumns(
Table.SelectColumns(Source,{"Name", "Folder Path", "Attributes"})
,{{"Folder Path", "Folder Path Full"}}),
    #"Expanded Attributes" = Table.ExpandRecordColumn(#"Removed Other Columns", "Attributes", {"Content Type", "Kind", "Size"}, {"Content Type", "Kind", "Size"}),
    #"fx_Size(KB)" = Table.AddColumn(#"Expanded Attributes", "Size(KB)", each [Size]/1024),
    #"fx_Size(MB)" = Table.AddColumn(#"fx_Size(KB)", "Size(MB)", each [Size]/1048576),
    #"fx_Size(GB)" = Table.AddColumn(#"fx_Size(MB)", "Size(GB)", each [Size]/1073741824),
    fx_FolderRoot = Table.AddColumn(#"fx_Size(GB)", "Folder Root", each valueRootFolderSearch),
    helper_LenFolderPathFull = Table.AddColumn(fx_FolderRoot, "LenFolderPathFull", each Text.Length([Folder Path Full])),
    fx_FolderDepth = Table.AddColumn(helper_LenFolderPathFull, "Folder Depth", each Text.End([Folder Path Full], [LenFolderPathFull]-lenRootFolderSearch+1)),
    #"helperList_ListFoldersDepth-Top2" = Table.AddColumn(fx_FolderDepth, "tmp_ListFoldersDepth", each List.Skip(
  List.FirstN(
    List.RemoveNulls(
      Text.Split([Folder Depth],"")
    )
  ,3)
,1)),
    #"ListFoldersDepth-Top2" = Table.TransformColumns(#"helperList_ListFoldersDepth-Top2", 
{"tmp_ListFoldersDepth", each "" & Text.Combine(List.Transform(_, Text.From), "") & ""
, type text}),
    #"Select Needed Columns" = Table.SelectColumns(#"ListFoldersDepth-Top2",{"Name", "Folder Root", "Folder Depth", "tmp_ListFoldersDepth", "Content Type", "Kind", "Size", "Size(KB)", "Size(MB)", "Size(GB)"}),
    #"rename_FoldersParent(1-2)" = Table.RenameColumns(#"Select Needed Columns",{{"tmp_ListFoldersDepth", "Folders Parent (1-2)"}})
in
    #"rename_FoldersParent(1-2)"

Folder File Sizes_xlsx.png

enter image description here

Folder File Sizes_xlsx2.png

enter image description here

I realize this question asked for file size analysis using CMD line. But if you are open to using PowerQuery (Excel add-in, versions 2010+) then you can create some pretty compelling file size analysis.

The script below can be pasted into a Blank Query; The only thing you’ll need to do is add a parameter named «paramRootFolderSearch» then add your value, such as «C:Usersbl0040Dropbox». I used this as a guide: MSSQLTips: Retrieve file sizes from the file system using Power Query.

This query provided the data for me to create a pivot table ([Folder Root]> [Folder Parent (1-2)], [Name]), and I was able to identify a few files that I could deleted which cleared up a lot of space in my directory.

Here is the M script for PowerQuery:

let
// Parmameters:
    valueRootFolderSearch = paramRootFolderSearch,
    lenRootFolderSearch = Text.Length(paramRootFolderSearch),
//

    Source = Folder.Files(paramRootFolderSearch),
    #"Removed Other Columns" = Table.RenameColumns(
Table.SelectColumns(Source,{"Name", "Folder Path", "Attributes"})
,{{"Folder Path", "Folder Path Full"}}),
    #"Expanded Attributes" = Table.ExpandRecordColumn(#"Removed Other Columns", "Attributes", {"Content Type", "Kind", "Size"}, {"Content Type", "Kind", "Size"}),
    #"fx_Size(KB)" = Table.AddColumn(#"Expanded Attributes", "Size(KB)", each [Size]/1024),
    #"fx_Size(MB)" = Table.AddColumn(#"fx_Size(KB)", "Size(MB)", each [Size]/1048576),
    #"fx_Size(GB)" = Table.AddColumn(#"fx_Size(MB)", "Size(GB)", each [Size]/1073741824),
    fx_FolderRoot = Table.AddColumn(#"fx_Size(GB)", "Folder Root", each valueRootFolderSearch),
    helper_LenFolderPathFull = Table.AddColumn(fx_FolderRoot, "LenFolderPathFull", each Text.Length([Folder Path Full])),
    fx_FolderDepth = Table.AddColumn(helper_LenFolderPathFull, "Folder Depth", each Text.End([Folder Path Full], [LenFolderPathFull]-lenRootFolderSearch+1)),
    #"helperList_ListFoldersDepth-Top2" = Table.AddColumn(fx_FolderDepth, "tmp_ListFoldersDepth", each List.Skip(
  List.FirstN(
    List.RemoveNulls(
      Text.Split([Folder Depth],"")
    )
  ,3)
,1)),
    #"ListFoldersDepth-Top2" = Table.TransformColumns(#"helperList_ListFoldersDepth-Top2", 
{"tmp_ListFoldersDepth", each "" & Text.Combine(List.Transform(_, Text.From), "") & ""
, type text}),
    #"Select Needed Columns" = Table.SelectColumns(#"ListFoldersDepth-Top2",{"Name", "Folder Root", "Folder Depth", "tmp_ListFoldersDepth", "Content Type", "Kind", "Size", "Size(KB)", "Size(MB)", "Size(GB)"}),
    #"rename_FoldersParent(1-2)" = Table.RenameColumns(#"Select Needed Columns",{{"tmp_ListFoldersDepth", "Folders Parent (1-2)"}})
in
    #"rename_FoldersParent(1-2)"

Folder File Sizes_xlsx.png

enter image description here

Folder File Sizes_xlsx2.png

enter image description here

You can just add up sizes recursively (the following is a batch file):

@echo off
set size=0
for /r %%x in (folder*) do set /a size+=%%~zx
echo %size% Bytes

However, this has several problems because cmd is limited to 32-bit signed integer arithmetic. So it will get sizes above 2 GiB wrong1. Furthermore it will likely count symlinks and junctions multiple times so it’s at best an upper bound, not the true size (you’ll have that problem with any tool, though).

An alternative is PowerShell:

Get-ChildItem -Recurse | Measure-Object -Sum Length

or shorter:

ls -r | measure -sum Length

If you want it prettier:

switch((ls -r|measure -sum Length).Sum) {
  {$_ -gt 1GB} {
    '{0:0.0} GiB' -f ($_/1GB)
    break
  }
  {$_ -gt 1MB} {
    '{0:0.0} MiB' -f ($_/1MB)
    break
  }
  {$_ -gt 1KB} {
    '{0:0.0} KiB' -f ($_/1KB)
    break
  }
  default { "$_ bytes" }
}

You can use this directly from cmd:

powershell -noprofile -command "ls -r|measure -sum Length"

1 I do have a partially-finished bignum library in batch files somewhere which at least gets arbitrary-precision integer addition right. I should really release it, I guess :-)

kaartic's user avatar

kaartic

5216 silver badges24 bronze badges

answered Oct 10, 2012 at 7:16

Joey's user avatar

15

There is a built-in Windows tool for that:

dir /s 'FolderName'

This will print a lot of unnecessary information but the end will be the folder size like this:

 Total Files Listed:
       12468 File(s)    182,236,556 bytes

If you need to include hidden folders add /a.

Mark Amery's user avatar

Mark Amery

137k78 gold badges401 silver badges450 bronze badges

answered Oct 26, 2016 at 7:47

Nir Duan's user avatar

Nir DuanNir Duan

6,0064 gold badges23 silver badges38 bronze badges

4

Oneliner:

powershell -command "$fso = new-object -com Scripting.FileSystemObject; gci -Directory | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName | sort Size -Descending | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName"

Same but Powershell only:

$fso = new-object -com Scripting.FileSystemObject
gci -Directory `
  | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName `
  | sort Size -Descending `
  | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName

This should produce the following result:

Size [MB]  FullName
---------  --------
580,08     C:myToolsmongo
434,65     C:myToolsCmder
421,64     C:myToolsmingw64
247,10     C:myToolsdotnet-rc4
218,12     C:myToolsResharperCLT
200,44     C:myToolsgit
156,07     C:myToolsdotnet
140,67     C:myToolsvscode
97,33      C:myToolsapache-jmeter-3.1
54,39      C:myToolsmongoadmin
47,89      C:myToolsPython27
35,22      C:myToolsrobomongo

answered Dec 19, 2017 at 21:09

frizik's user avatar

frizikfrizik

1,6261 gold badge12 silver badges17 bronze badges

5

I suggest to download utility DU from the Sysinternals Suite provided by Microsoft at this link
http://technet.microsoft.com/en-us/sysinternals/bb896651

usage: du [-c] [-l <levels> | -n | -v] [-u] [-q] <directory>
   -c     Print output as CSV.
   -l     Specify subdirectory depth of information (default is all levels).
   -n     Do not recurse.
   -q     Quiet (no banner).
   -u     Count each instance of a hardlinked file.
   -v     Show size (in KB) of intermediate directories.


C:SysInternals>du -n d:temp

Du v1.4 - report directory disk usage
Copyright (C) 2005-2011 Mark Russinovich
Sysinternals - www.sysinternals.com

Files:        26
Directories:  14
Size:         28.873.005 bytes
Size on disk: 29.024.256 bytes

While you are at it, take a look at the other utilities. They are a life-saver for every Windows Professional

answered Oct 10, 2012 at 7:16

Steve's user avatar

SteveSteve

212k22 gold badges229 silver badges286 bronze badges

6

If you have git installed in your computer (getting more and more common) just open MINGW32 and type: du folder

answered May 8, 2014 at 14:02

Custodio's user avatar

CustodioCustodio

8,41415 gold badges80 silver badges115 bronze badges

1

Here comes a powershell code I write to list size and file count for all folders under current directory. Feel free to re-use or modify per your need.

$FolderList = Get-ChildItem -Directory
foreach ($folder in $FolderList)
{
    set-location $folder.FullName
    $size = Get-ChildItem -Recurse | Measure-Object -Sum Length
    $info = $folder.FullName + "    FileCount: " + $size.Count.ToString() + "   Size: " + [math]::Round(($size.Sum / 1GB),4).ToString() + " GB"
    write-host $info
}

answered Oct 9, 2018 at 4:56

Ryan Lee's user avatar

Ryan LeeRyan Lee

1111 silver badge2 bronze badges

5

I recommend using https://github.com/aleksaan/diskusage utility which I wrote. Very simple and helpful. And very fast.

Just type in a command shell

diskusage.exe -path 'd:/go; d:/Books'

and get list of folders arranged by size

  1.| DIR: d:/go      | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/Books   | SIZE:  14.01 Mb   | DEPTH: 1 

This example was executed at 272ms on HDD.

You can increase depth of subfolders to analyze, for example:

diskusage.exe -path 'd:/go; d:/Books' -depth 2

and get sizes not only for selected folders but also for its subfolders

  1.| DIR: d:/go            | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/go/pkg        | SIZE: 212.88 Mb   | DEPTH: 2 
  3.| DIR: d:/go/src        | SIZE:  62.57 Mb   | DEPTH: 2 
  4.| DIR: d:/go/bin        | SIZE:  30.44 Mb   | DEPTH: 2 
  5.| DIR: d:/Books/Chess   | SIZE:  14.01 Mb   | DEPTH: 2 
  6.| DIR: d:/Books         | SIZE:  14.01 Mb   | DEPTH: 1 
  7.| DIR: d:/go/api        | SIZE:   6.41 Mb   | DEPTH: 2 
  8.| DIR: d:/go/test       | SIZE:   5.11 Mb   | DEPTH: 2 
  9.| DIR: d:/go/doc        | SIZE:   4.00 Mb   | DEPTH: 2 
 10.| DIR: d:/go/misc       | SIZE:   3.82 Mb   | DEPTH: 2 
 11.| DIR: d:/go/lib        | SIZE: 358.25 Kb   | DEPTH: 2 

*** 3.5Tb on the server has been scanned for 3m12s**

Ro Yo Mi's user avatar

Ro Yo Mi

14.6k5 gold badges34 silver badges43 bronze badges

answered Aug 24, 2018 at 16:17

Alexander Anufriev's user avatar

3

Try:

SET FOLDERSIZE=0
FOR /F "tokens=3" %A IN ('DIR "C:Program Files" /a /-c /s ^| FINDSTR /C:" bytes" ^| FINDSTR /V /C:" bytes free"') DO SET FOLDERSIZE=%A

Change C:Program Files to whatever folder you want and change %A to %%A if using in a batch file

It returns the size of the whole folder, including subfolders and hidden and system files, and works with folders over 2GB

It does write to the screen, so you’ll have to use an interim file if you don’t want that.

answered Nov 14, 2017 at 8:47

FrinkTheBrave's user avatar

FrinkTheBraveFrinkTheBrave

3,87410 gold badges45 silver badges55 bronze badges

I guess this would only work if the directory is fairly static and its contents don’t change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn’t want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

answered Dec 6, 2017 at 19:41

Steve's user avatar

SteveSteve

315 bronze badges

1

This code is tested. You can check it again.

@ECHO OFF
CLS
SETLOCAL
::Get a number of lines contain "File(s)" to a mytmp file in TEMP location.
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /C "File(s)" >%TEMP%mytmp
SET /P nline=<%TEMP%mytmp
SET nline=[%nline%]
::-------------------------------------
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /N "File(s)" | FIND "%nline%" >%TEMP%mytmp1
SET /P mainline=<%TEMP%mytmp1
CALL SET size=%mainline:~29,15%
ECHO %size%
ENDLOCAL
PAUSE

answered Aug 10, 2013 at 14:37

Chienvela's user avatar

1

I got du.exe with my git distribution. Another place might be aforementioned Microsoft or Unxutils.

Once you got du.exe in your path. Here’s your fileSizes.bat :-)

@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"

___________
DIRECTORIES
37M     Alps-images
12M     testfolder
_____
FILES
765K    Dobbiaco.jpg
1.0K    testfile.txt
_____
TOTAL
58M    D:picturessample

answered Oct 24, 2015 at 17:13

Frank N's user avatar

Frank NFrank N

9,3084 gold badges76 silver badges107 bronze badges

I think your only option will be diruse (a highly supported 3rd party solution):

Get file/directory size from command line

The Windows CLI is unfortuntely quite restrictive, you could alternatively install Cygwin which is a dream to use compared to cmd. That would give you access to the ported Unix tool du which is the basis of diruse on windows.

Sorry I wasn’t able to answer your questions directly with a command you can run on the native cli.

answered Oct 10, 2012 at 7:22

Illizian's user avatar

IllizianIllizian

4841 gold badge5 silver badges13 bronze badges

4

::Get a number of lines that Dir commands returns (/-c to eliminate number separators: . ,)
[«Tokens = 3» to look only at the third column of each line in Dir]

FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO set /a i=!i!+1

Number of the penultimate line, where is the number of bytes of the sum of files:

set /a line=%i%-1

Finally get the number of bytes in the penultimate line — 3rd column:

set i=0
FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO (
  set /a i=!i!+1
  set bytes=%%a
  If !i!==%line% goto :size  
)
:size
echo %bytes%

As it does not use word search it would not have language problems.

Limitations:

  • Works only with folders of less than 2 GB (cmd does not handle numbers of more than 32 bits)
  • Does not read the number of bytes of the internal folders.

answered Jun 2, 2017 at 14:08

Gustavo Davico's user avatar

The following script can be used to fetch and accumulate the size of each file under a given folder.
The folder path %folder% can be given as an argument to this script (%1).
Ultimately, the results is held in the parameter %filesize%

@echo off
SET count=1
SET foldersize=0
FOR /f "tokens=*" %%F IN ('dir /s/b %folder%') DO (call :calcAccSize "%%F")
echo %filesize%
GOTO :eof

:calcAccSize
 REM echo %count%:%1
 REM set /a count+=1
 set /a foldersize+=%~z1
 GOTO :eof

Note: The method calcAccSize can also print the content of the folder (commented in the example above)

answered Mar 25, 2019 at 8:40

Lior Kirshner's user avatar

So here is a solution for both your requests in the manner you originally asked for.
It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.

@echo off
setlocal enabledelayedexpansion
set "vSearch=Files :"

For %%i in (%*) do (
    set "vSearch=Files :"
    For /l %%M in (1,1,2) do ( 
        for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
            if /i "%%M"=="1" (
                set "filecount=%%A"
                set "vSearch=Bytes :"
            ) else (
                set "foldersize=%%A%%B"
            )
        )
    )
    echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
    REM remove the word "REM" from line below to output to txt file
    REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
)
pause

To be able to use this batch file conveniently put it in your SendTo folder.
This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.

To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.

explorer C:Users%username%AppDataRoamingMicrosoftWindowsSendTo

answered May 15, 2019 at 5:26

julesverne's user avatar

julesvernejulesverne

3921 gold badge8 silver badges17 bronze badges

3

The following one-liners can be used to determine the size of a folder.

The post is in Github Actions format, indicating which type of shell is used.

shell: pwsh
run: |
  Get-ChildItem -Path C:temp -Recurse | Measure-Object -Sum Length


shell: cmd
run: |
  powershell -noprofile -command "'{0:N0}' -f (ls C:temp -r | measure -s Length).Sum"

answered Mar 19, 2021 at 19:10

Jens A. Koch's user avatar

Jens A. KochJens A. Koch

38.9k13 gold badges110 silver badges137 bronze badges

Open windows CMD and run follow command

dir /s c:windows

answered Jul 2, 2021 at 6:59

Tuan Le Anh's user avatar

2

It’s better to use du because it’s simple and consistent.

install scoop: iwr -useb get.scoop.sh | iex

install busybox: scoop install busybox

get dir size: du -d 0 . -h

answered Apr 1, 2022 at 1:35

SodaCris's user avatar

SodaCrisSodaCris

1992 silver badges3 bronze badges

1

I was at this page earlier today 4/27/22, and after trying DU by SysInternals (https://learn.microsoft.com/en-us/sysinternals/downloads/du) and piping the output etc etc. I said «Didn’t I have to do this in VBscript? I got this to work for total size of ISOroot folder and all subfolders. Replace the Folder fullpath with your own. It’s very fast.

GetFolderSize.vbs

 Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder("C:XPECustomx64IsoRoot")
    s = UCase(f.Name) & " uses " & f.size & " bytes."
    MsgBox s, 0, "Folder Size Info"

s=  FormatNumber(f.size/1024000,2) & " MB"
    MsgBox s, 0, "Folder Size Info"

s=  FormatNumber(f.size/1073741824,2) & " GB"
    MsgBox s, 0, "Folder Size Info"

answered Apr 27, 2022 at 15:22

Tony4219's user avatar

Use Windows Robocopy.

Put this in a batch file:

@echo off
pushd "%~dp0"
set dir="C:Temp"
for /f "tokens=3" %%i in ('robocopy /l /e /bytes %dir% %dir% ^| findstr Bytes') do @echo %%i
pause

Set the path for your folder in the dir variable.

The for loop gets the 3rd string using tokens=3, which is the size in bytes, from the robocopy findstr command.

The /l switch in robocopy only lists the output of the command, so it doesn’t actually run.

The /e switch in robocopy copies subdirectories including empty ones.

The /bytes switch in robocopy copies subdirectories including empty ones.
You can omit the /bytes switch to get the size in default folder properties sizes (KB, MB, GB…)

The findstr | Bytes command finds the output of robocopy command which contains total folder size.

And finally echo the index %%i to the console.

If you need to save the folder size to a variable replace

do @echo %%i

with

set size=%%i

If you want to send the folder size to another program through clipboard:

echo %size% | clip

If you need to get the current folder size put the batch file into that folder and remove set dir="C:Temp" and replace both %dir% with %cd%, which stands for current directory, like this:

@echo off
pushd "%~dp0"
for /f "tokens=3" %%i in ('robocopy /l /e /bytes "%cd%" "%cd%" ^| findstr Bytes') do @echo %%i
pause

answered Jan 19 at 2:47

Mister Robato's user avatar

I solved similar problem. Some of methods in this page are slow and some are problematic in multilanguage environment (all suppose english).
I found simple workaround using vbscript in cmd. It is tested in W2012R2 and W7.

>%TEMP%_SFSTMP$.VBS ECHO/Set objFSO = CreateObject("Scripting.FileSystemObject"):Set objFolder = objFSO.GetFolder(%1):WScript.Echo objFolder.Size
FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%_SFSTMP$.VBS') DO (SET "S_=%%?"&&(DEL %TEMP%_SFSTMP$.VBS))

It set environment variable S_. You can, of course, change last line to directly display result to e.g.

FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%_SFSTMP$.VBS') DO (ECHO "Size of %1 is %%?"&&(DEL %TEMP%_SFSTMP$.VBS))

You can use it as subroutine or as standlone cmd. Parameter is name of tested folder closed in quotes.

answered Mar 19, 2016 at 13:49

arpi's user avatar

Easiest method to get just the total size is powershell, but still is limited by fact that pathnames longer than 260 characters are not included in the total

answered Feb 2, 2015 at 19:22

ray's user avatar

1

I realize this question asked for file size analysis using CMD line. But if you are open to using PowerQuery (Excel add-in, versions 2010+) then you can create some pretty compelling file size analysis.

The script below can be pasted into a Blank Query; The only thing you’ll need to do is add a parameter named «paramRootFolderSearch» then add your value, such as «C:Usersbl0040Dropbox». I used this as a guide: MSSQLTips: Retrieve file sizes from the file system using Power Query.

This query provided the data for me to create a pivot table ([Folder Root]> [Folder Parent (1-2)], [Name]), and I was able to identify a few files that I could deleted which cleared up a lot of space in my directory.

Here is the M script for PowerQuery:

let
// Parmameters:
    valueRootFolderSearch = paramRootFolderSearch,
    lenRootFolderSearch = Text.Length(paramRootFolderSearch),
//

    Source = Folder.Files(paramRootFolderSearch),
    #"Removed Other Columns" = Table.RenameColumns(
Table.SelectColumns(Source,{"Name", "Folder Path", "Attributes"})
,{{"Folder Path", "Folder Path Full"}}),
    #"Expanded Attributes" = Table.ExpandRecordColumn(#"Removed Other Columns", "Attributes", {"Content Type", "Kind", "Size"}, {"Content Type", "Kind", "Size"}),
    #"fx_Size(KB)" = Table.AddColumn(#"Expanded Attributes", "Size(KB)", each [Size]/1024),
    #"fx_Size(MB)" = Table.AddColumn(#"fx_Size(KB)", "Size(MB)", each [Size]/1048576),
    #"fx_Size(GB)" = Table.AddColumn(#"fx_Size(MB)", "Size(GB)", each [Size]/1073741824),
    fx_FolderRoot = Table.AddColumn(#"fx_Size(GB)", "Folder Root", each valueRootFolderSearch),
    helper_LenFolderPathFull = Table.AddColumn(fx_FolderRoot, "LenFolderPathFull", each Text.Length([Folder Path Full])),
    fx_FolderDepth = Table.AddColumn(helper_LenFolderPathFull, "Folder Depth", each Text.End([Folder Path Full], [LenFolderPathFull]-lenRootFolderSearch+1)),
    #"helperList_ListFoldersDepth-Top2" = Table.AddColumn(fx_FolderDepth, "tmp_ListFoldersDepth", each List.Skip(
  List.FirstN(
    List.RemoveNulls(
      Text.Split([Folder Depth],"")
    )
  ,3)
,1)),
    #"ListFoldersDepth-Top2" = Table.TransformColumns(#"helperList_ListFoldersDepth-Top2", 
{"tmp_ListFoldersDepth", each "" & Text.Combine(List.Transform(_, Text.From), "") & ""
, type text}),
    #"Select Needed Columns" = Table.SelectColumns(#"ListFoldersDepth-Top2",{"Name", "Folder Root", "Folder Depth", "tmp_ListFoldersDepth", "Content Type", "Kind", "Size", "Size(KB)", "Size(MB)", "Size(GB)"}),
    #"rename_FoldersParent(1-2)" = Table.RenameColumns(#"Select Needed Columns",{{"tmp_ListFoldersDepth", "Folders Parent (1-2)"}})
in
    #"rename_FoldersParent(1-2)"

Folder File Sizes_xlsx.png

enter image description here

Folder File Sizes_xlsx2.png

enter image description here

How to find the size of a file

In Windows, we can use dir command to get the file size.

C:>dir vlcplayer.exe
Directory of C:

02/22/2011  10:30 PM        20,364,702 vlcplayer.exe
1 File(s)     20,364,702 bytes
0 Dir(s)  86,917,496,832 bytes free

But there is no option/switch to print only the file size.

Get size for all the files in a directory

Dir command accepts wild cards. We can use ‘*” to get the file sizes for all the files in a directory.

C:>dir C:WindowsFonts
Volume in drive C is Windows 7
Volume Serial Number is 14A1-91B9

Directory of C:WindowsFonts

06/11/2009  02:13 AM            10,976 8514fix.fon
06/11/2009  02:13 AM            10,976 8514fixe.fon
06/11/2009  02:13 AM            11,520 8514fixg.fon
06/11/2009  02:13 AM            10,976 8514fixr.fon
06/11/2009  02:13 AM            11,488 8514fixt.fon
06/11/2009  02:13 AM            12,288 8514oem.fon
06/11/2009  02:13 AM            13,248 8514oeme.fon
06/11/2009  02:13 AM            12,800 8514oemg.fon

We can also get size for files of certain type. For example, to get file size for mp3 files, we can run the command ‘dir *.mp3‘.

The above command prints file modified time also. To print only the file name and size we can run the below command from a batch file.

@echo off

for /F "tokens=4,5" %%a in ('dir c:windowsfonts') do echo %%a %%b

Save the above commands to a text file, say filesize.bat, and run it from command prompt.

Get directory size

There’s no Windows built in command to find directory size.  But there is a tool called diruse.exe which can be used to get folder size. This tool is part of XP support tools.  This command can be used to get directory size. This command’s syntax is given below.

diruse.exe   directory_name

C:>diruse c:windows

Size  (b)  Files  Directory
12555896050  64206  SUB-TOTAL:  C:WINDOWS
12555896050  64206  TOTAL:  C:WINDOWS

As you can see in the above example, diruse prints the directory size in bytes and it also prints the number of files in the directory(it counts the number of files in the sub folders also)

To get the directory size in mega bytes we can add /M switch.

C:>diruse /M C:Windows

Size (mb)  Files  Directory
11974.24  64206  SUB-TOTAL: C:WINDOWS
11974.24  64206  TOTAL: C:WINDOWS

Download XP Support Tools

Though the tool is intended for XP and Server 2003, I have observed that it works on Windows 7 also.  The above examples were indeed from a Windows 7 computer.

Я хочу использовать командную строку Windows, чтобы вычислить размер всех файлов в папке и подпапке. Обычно я делаю это, щелкая правой кнопкой мыши по папке и выбирая «Свойства», но я хочу сделать это в командной строке.

Какую команду я могу использовать?

Вы захотите использовать dir /a/s чтобы он включал каждый файл, включая системные и скрытые файлы. Это даст вам общий размер, который вы хотите.

изменён RockPaperLizard3k

ответ дан RockPaperLizard3k

Вы можете использовать PowerShell!

$totalsize = [long]0
Get-ChildItem -File -Recurse -Force -ErrorAction SilentlyContinue | % {$totalsize += $_.Length}
$totalsize

Это повторяется по всему текущему каталогу (игнорируя каталоги, которые нельзя ввести) и суммирует размеры каждого файла. Затем он печатает общий размер в байтах.

Уплотненный однострочный:

$totalsize=[long]0;gci -File -r -fo -ea Silent|%{$totalsize+=$_.Length};$totalsize

На моей машине это выглядит немного быстрее, чем dir /s /a , поскольку он не выводит информацию о каждом объекте на экран.

Чтобы запустить его из обычной командной строки:

powershell -command "$totalsize=[long]0;gci -File -r -fo -ea Silent|%{$totalsize+=$_.Length};$totalsize"

Нет такой команды, встроенной в командную строку DOS или Windows. В Linux есть команда du (D isk U sage).

Линейка инструментов Microsoft Sysinternals имеет инструмент, который примерно эквивалентен du в Linux. Это также называется du . ;)

Размер папки можно рассчитать с помощью следующего пакетного сценария:

@echo off
setlocal enabledelayedexpansion

set size=0
for /f "tokens=*" %%x in ('dir /s /a /b %1') do set /a size+=%%~zx
echo.!size!

endlocal

Вы все еще можете использовать утилиту командной строки diruse.exe из набора ресурсов Windows 2000, доступного здесь:

https://support.microsoft.com/en-us/kb/927229

Работает на Windows 8.1 без проблем.

изменён Twisty Impersonator18k

Просто откройте power shell и выполните du -sh <directory> без необходимости устанавливать сторонние или sys-internals. В Power-shell вы можете запускать некоторые простые Linux-подобные команды, такие как команды ls или du, некоторые из переключателей не будут работать, как ls -alt будет ошибка, поскольку powershell не знает, что такое -alt …

dir /s Перечислит размеры всех файлов и файлов во всех подпапках

Команда «dir» предоставляет размер файла, дату последнего изменения и время текущего каталога. Сначала попробуйте перейти в каталог, размер которого вы хотите использовать, используя команду cd , затем используйте команду dir .

C:>dir 

Перечисляет размер файла, дату и время последнего изменения всех файлов и каталогов в каталоге, в котором вы находитесь в данный момент, в алфавитном порядке.

На чтение 4 мин. Просмотров 708 Опубликовано 15.12.2019

Содержание

  1. Как узнать размер папки через командную строку? / How check size folder in command prompt?
  2. Как узнать размер и дату файла из командной строки : 12 комментариев
  3. Предлагаю ознакомиться с предложениями моих партнёров

Как узнать размер папки через командную строку? / How check size folder in command prompt?

Узнать размер папки в Microsoft Windows достаточно просто через графический интерфейс.

Для этого, достаточно выделить интересующую папку левой кнопкой мыши, далее нажать правой кнопкой мыши и выбрать пункт Свойства

В окне Свойства указан размер Папки.

Узнать размер папки через командную строку немного сложнее.

Для этого, необходимо создать . cmd файл с содержимым:

@echo off

setlocal enableextensions disabledelayedexpansion

set «source=c:Folder»

if not defined target set «source=%cd%»

set «size=0»

for /f «tokens=3,5» %%a in (‘

dir /a /s /w /-c «%source%»

^| findstr /b /l /c:» «

‘) do if «%%b»==»» set «size=%%a»

echo % size %

Где C : Folder — может быть заменен на интересующую вас папку. Отображение размера будет выполнено в байтах.

Learn the size of the folder in Microsoft Windows is quite simple through the graphical interface. To do this, it is enough to select the folder of interest with the left mouse button, then right mouse button click and click Properties


The Folder size is specified in the Properties.

Finding out the size of a folder via the command line is a bit more complicated.

To do this, you must create .cmd file with content:

rem @echo off

setlocal enableextensions disabledelayedexpansion

set «source=c:Folder»

if not defined target set «source=%cd%»

set «size=0»

for /f «tokens=3,5» %%a in (‘

dir /a /s /w /-c «%source%»

^| findstr /b /l /c:» «

‘) do if «%%b»==»» set «size=%%a»

echo %size%

Where C:Folder — can be replaced to the required folder. The size will be displayed in bytes.

Супер мини статья ��

Простейший способ получить размер файла из командной строки Windows:

из хелпа по команде For в Cmd:

zI — переменная %I расширяется до размера файла

Аналогично для даты (модификации) файла:

из хелпа по команде For в Cmd:

tI — переменная %I расширяется до даты /времени файла

А вообще команда for /? очень полезная.

Как узнать размер и дату файла из командной строки : 12 комментариев

Добрый день
На команду:
for %i in (1.txt) do echo %

Windows XP3 сообщает:

ti was unexpected at this time.

Подскажите пожалуйста, что в команде указанно не верно.

@ Саша:
вы исполняете эту команду из пакетного файла?

Не из пакетного файла это вообще не будет работать.
А в пакетном файле к переменным внутри FOR добавляется еще один %

for %%i in (1.txt) do echo %%

Совершенно верно. В статье речь только о командной строке.

это дата изменения файла, а не создания…

Добрый день!
Помогите, пожалуйста.
Задача такая, нужно выбрать из каталога файлы *.log с сегодняшней датой и пробежаться по ним командой find….

ta «%%a»
exit
:cmp
if %1==%date% find «chto_ishem» %3
exit /b

А не подскажете решение для такой задачки? Нужно сравнить два файла и заменить более старый более новым (проще говоря, выполнить обновление). Проблема в том, что сравнение дат как строк дает неверный результат для случая, скажем: «06.10.2011» будет меньше «07.09.2011» (6 октября меньше 7 сентября).

@ Гость:
Т.к. универсальный метод работы с датами из командной строки Windows сделать довольно-таки проблематично из-за различных региональных настроек, я бы сделал так: скопировал оба файла под разными именами (естественно) в одну папку, отсортировал по дате, удалил самый старый, оставшийся перенес куда надо под нужным именем. Это всё алгоритм, естественно, для выполнения из cmd/bat файла.
Чуть позже будет статья как удалять самые старые файлы, что-то подобной этой статье, но под Windows

Как узнать размер папок в Windows и сделать экспорт этой информации в txt ?

Может понадобится, если Вы захотите проверить, что на диске больше всего занимает места. Узнать размер папок в Windows можна с помощью скрипта на cmd.

Предлагаю ознакомиться с предложениями моих партнёров

В данном примере, в файл D: empautoskinfo.txt будет записана информация о размере директории E:vektor6.local, и всех вложеных в неё папок и подпапок

Если Вам не нужна подробная информация о размере вложеных поддиректориях, надо закоменировать строку

Будет выведена информация о размере указаной директории и размеры вложеных в неё папок

Ну а если вам надо записать в файл размер только одной указаной в начале директории, то закомментируйте ещё и эту строку

11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

1

Определить размер папки

07.01.2013, 14:44. Показов 31686. Ответов 46


Спасибо всем! Получается!
Только я терь к другой немножко схеме подошёл , можно из этого кода выдрать токо то что считывает размер папки (с под папками) и выводит на экран?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Dragokas

Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

07.01.2013, 17:08

2

Цитата
Сообщение от Dragokas
Посмотреть сообщение

:GetFolderSize %1-Folder_Name %2-Var_Name.Size

в заглавии как-бы описание.

Bash
1
2
3
4
5
@echo off
Set folder=c:temp
Call :GetFolderSize "%folder%" Size
Echo Size=%Size% Bytes
pause

Расширенный пример этой функции с выводом на экран разбивки на Кб и Мб есть здесь: Тонкости языка, редкие команды и сложные скрипты



1



Jeka_Osokin

11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

07.01.2013, 17:35

 [ТС]

3

Короче

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Echo Off
SetLocal enabledelayedexpansion
Set /p D=?
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%D%" /-C /S /A:-D') Do (
If !flag!==1 Set dirsize=%%c
If "%%b"=="файлов:" (Set flag=1) else (Set flag=0)
)
Set /a dirsizeT=dirsize+0
If Not "%dirsizeT%"=="%dirsize%" Echo Число %dirsize% слишком велико для обработки в CMD&Pause>nul&Exit
Set kb=1024
Set /a mb=kb*kb, gb=kb*kb*kb, dirsizeMB=dirsize/mb, ostMB=dirsize%%mb*100/mb
Rem Set /a dirsizeGB=dirsize/gb, ostGB=dirsize%%gb*10/gb
Echo %dirsizeMB%,%ostMB% МБ
Rem Echo %dirsizeGB%,%ostGB% ГБ
Pause>nul

И терь осталось какбы он не говорил мне что «Echo Число слишком велико для обработки в CMD» сделать…



0



Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

07.01.2013, 21:13

4

Озвучьте, пожалуйста, полностью задание.

Размер папки в байтах Вы получили — это переменная dirsize, начиная со строки № 8.
Остальное по сути лишнее.



0



Jeka_Osokin

11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

07.01.2013, 22:42

 [ТС]

5

Полностью дак полностью:
У меня есть длинный код

Windows Batch file
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
for /f "skip=4 tokens=1-3" %%a in ('Dir "%p%" /-C /S 2^>nul') do (
set pap=%%~na
If !flag!==1 set dirsize=%%c& set nn=%%a
If "%%b"=="файлов:" (Set flag=1) Else (Set flag=0))
set Cnt=!dirsize!
Call:UDIV2 %Cnt% dirsizeMB  20
Call:UMUL2 %dirsizeMB% CntT 20
Call:SUM %Cnt% -%CntT% ost
Set/a $.mb=(%ost%*100)/(1024*1024)
Set "$.mb=0%$.mb%"& Set "$.mb=!$.mb:~-2!"
if errorlevel 6 (
cls
echo.
echo                             Информация GTA IV
echo  Размер %dirsizeMB%,%$.mb% Мб
echo  Установлена по пути:
echo  %u%
goto usmd
)
cls
echo.
echo                                   Установка
echo.
echo   Найдено !nn! файлов, размер которых %dirsizeMB%,%$.mb% Мб
echo.
echo   Начать установку
echo   Удаление мода
echo   Назад
choice /C 123 /N
if errorlevel 3 goto re
if errorlevel 2 goto ud
if errorlevel 1 goto set
:SUM  %uint%  %uint%  %VarRes%
(set "$a=%~1"& set "$b=%~2"
if "!$a:~,1!"=="-" (set "$az=-"&set "$a=!$a:-=!") else set "$az="
if "!$b:~,1!"=="-" (set "$bz=-"&set "$b=!$b:-=!") else set "$bz="
for /f "tokens=* delims=0" %%i in ("!$a:~-9!") do set/a "$al=%%i+0"&set/a "$ah=!$a:~,-9!+0"
for /f "tokens=* delims=0" %%i in ("!$b:~-9!") do set/a "$bl=%%i+0"&set/a "$bh=!$b:~,-9!+0"
set/a "$sl=(!$az!!$al!)+(!$bz!!$bl!)"&set/a $p=!$sl:~,-9!+0&set/a "$sl=!$sl!-(!$p!000000000)"
set/a "$sh=(!$az!!$ah!)+(!$bz!!$bh!)+(!$p!+0)"
if !$sh! gtr 0 if !$sl! lss 0 set/a $sh-=1& set/a "$sl=(1000000000+!$sl!)"
if !$sh! lss 0 if !$sl! gtr 0 set/a $sh+=1& set/a "$sl=(!$sl!-1000000000)"
for /f "delims=0123456789" %%i in ("!$sh!!$sl!") do set "$z=%%i"
if !$sh! equ 0 if !$sl! equ 0 set "$z=0"
set "$sl=00000000!$sl:-=!")
for /f "tokens=* delims=0" %%i in ("!$sh:-=!!$sl:~-9!") do ENDLOCAL& set "%~3=%$z%%%i"
GoTo:EOF
:UDIV2  %uint% %VarRes% %uint%
(set "$a=%~1"& set/a "$c=%~3+0"& if !$c! equ 0 set "$c=1"
for /f "tokens=* delims=0" %%i in ("!$a:~-9!") do set/a "$al=%%i+0,$ah=!$a:~,-9!+0"
for /l %%i in (1,1,!$c!) do (
set/a "$p=$ah&1,$ah>>=1,$al>>=1"
if !$p!==1 set/a $al=$al+500000000)
set "$z="& if !$ah! equ 0 if !$al! equ 0 set "$z=0")
for /f "tokens=* delims=0" %%i in ("!$ah!!$al!") do ENDLOCAL& set "%~2=%$z%%%i"
GoTo:EOF
:UMUL2  %uint% %VarRes% %uint%
(set %~2=%~1& set/a "$c=%~3+0"& if !$c! equ 0 set "$c=1"
for /l %%i in (1,1,!$c!) do Call:SUM !%~2! !%~2! %~2
for /f %%i in ("!%~2!") do ENDLOCAL& set "%~2=%%i")
GoTo:EOF

+ Этот

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Echo Off
SetLocal enabledelayedexpansion
Set /p D=?
cls
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%D%" /-C /S /A:-D') Do (
If !flag!==1 Set dirsize=%%c
If "%%b"=="файлов:" (Set flag=1) else (Set flag=0)
)
Set /a dirsizeT=dirsize+0
If Not "%dirsizeT%"=="%dirsize%" Echo Число %dirsize% слишком велико для обработки в CMD&Pause>nul
Set kb=1024
Set /a mb=kb*kb, gb=kb*kb*kb, dirsizeMB=dirsize/mb, ostMB=dirsize%%mb*100/mb
Rem Set /a dirsizeGB=dirsize/gb, ostGB=dirsize%%gb*10/gb
Echo %dirsizeMB%,%ostMB% МБ
Rem Echo %dirsizeGB%,%ostGB% ГБ
Pause>nul

Первый всё делает ,но он большущий , я думал если бы написать более мелкий но с той-же функцией!
Второй хоть и подсчитывает ,но если число превысит фиг знает какое значение , то он пишет мне ту фигню…
Вы умный и может сможете мне помочь?



0



Dragokas

Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

08.01.2013, 02:58

6

Кхм.
Нет, не на столько, как бы хотелось )

Я так понял Вам нужно, чтобы ответ писало в МегаБайтах, но при этом математика не выдавала ошибок.

(*немного почесав голову*)

Так достаточно коротко: ?

Bash
1
2
3
4
5
6
7
@Echo Off
SetLocal enabledelayedexpansion
Set D=l:Bash
For /F "tokens=1-3" %%a IN ('Dir "%D%" /-C/S/A:-D') Do Set DirSize=!n2!& Set n2=%%c
Set DirSize=%DirSize:~0,-6%
Echo Size of %D% is %DirSize% MB.
pause



2



11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

08.01.2013, 12:06

 [ТС]

7

Цитата
Сообщение от Dragokas
Посмотреть сообщение

достаточно коротко: ?

О Господи ну наконец то! Спасибо огромное вам!!! , Всё решено! , мелкий вопросик (так просто):
Вот когда тыкаешь на свойства папки и видишь размер ,то он показывает
Размер: 8,00 ГБ (8 596 143 292 байт)
На диске: 8,00 ГБ (8 599 232 512 байт)
Чё он сначала говорит что размер 8 ГБ ,а тут же пишет 8,5 ГБ ? (и ваш код как раз размер который в скобках считает…)



0



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

08.01.2013, 12:40

8

Код

1 Кб = 1024Байта
1 Мб = 1024*1024=1048576 Байт
1 Гб = 1048576*1024=1073741824 Байт
8 596 143 292 Байт = 8 596 143 292 / 1073741824 =  8,005 Гб

Всё. Просто занимательная информатика.



0



Dragokas

Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

08.01.2013, 12:52

9

Лучший ответ Сообщение было отмечено Joey как решение

Решение

Вам вроде как хотелось по-короче.
Ну если нужно и с сотыми, тогда так:

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Echo Off
SetLocal enabledelayedexpansion
Set D=l:Bash
For /F "tokens=1-3" %%a IN ('Dir "%D%" /-C/S/A:-D') Do Set DirSize=!n2!& Set n2=%%c
CAll :var_count "%DirSize%" VarC
Set /A VarC-=6
if %VarC% LEQ 0 (Set DirSizeMB=0) else (Set DirSizeMB=%DirSize:~0,-6%)
if %VarC% GEQ 1 Set DirSizeMB=%DirSizeMB%,!DirSize:~%VarC%,2!
Echo Size of %D% is %DirSizeMB% MB.
pause& Goto :eof
 
:var_count %1-Var.Value %2-Var.Count.Result
::Определяет длину переменной
set var=%~1
if not defined var exit /b
set var=%var:~1%
set /a %~2+=1
call :var_count "%var%" %~2
exit /b



1



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

08.01.2013, 13:08

10

В смысле? Я просто пример привёл, почему 8 596 143 292 Байт это 8 Гб и всё.



0



11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

08.01.2013, 13:49

 [ТС]

11

Цитата
Сообщение от Dragokas
Посмотреть сообщение

нужно и с сотыми

Да нееее! Всё норм , FraidZZ — уже дал ответ , меня щас интересует как сделать чтоб он исключал папки «backup» и «mod»



0



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

08.01.2013, 13:56

12

Отрывок кода приведи, где нужно исключение



0



Jeka_Osokin

11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

08.01.2013, 14:47

 [ТС]

13

Windows Batch file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
set p=%u%
 
:sco
For /F "tokens=1-3" %%a IN ('Dir "%p%" /-C/S/A:-D') Do Set DirSize=!n2!& Set n2=%%c
Set DirSize=%DirSize:~0,-6%
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%p%" /-C /S /A:-D^|find /I "файлов"') Do (
set fi=%%a
)
if errorlevel 6 (
cls
echo.
echo                             Информация GTA IV
echo  Размер %DirSize% MB
echo  Установлена по пути:
echo  %u%
goto usmd
)

Значит: Сначала ставит что п=у (у в данном случае является путём в реестре к каталогу) ,потом показывает размер папки (%u%)
Вот во время этого подсчёта он должен исключать папки «mod» и «backup»

Добавлено через 7 минут
А можно ещё сделать чтобы он считал в другом формате как
тут расписано?



0



Eva Rosalene

Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

08.01.2013, 16:09

14

Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
set p=%u%
 
:sco
attrib -R * /S /D
attrib +R mod
attrib +R backup
For /F "tokens=1-3" %%a IN ('Dir "%p%" /-C/S/A:-D-R') Do Set DirSize=!n2!& Set n2=%%c
Set DirSize=%DirSize:~0,-6%
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%p%" /-C /S /A:-D-R^|find /I "файлов"') Do (
set fi=%%a
)
attrib -R * /S /D
if errorlevel 6 (
cls
echo.
echo                             Информация GTA IV
echo  Размер %DirSize% MB
echo  Установлена по пути:
echo  %u%
goto usmd
)

Добавил команды attrib. А также внимательно сравни мою 7ую строчку с 4ой твоей, а также 9ую с 6ой.

Цитата
Сообщение от Jeka_Osokin
Посмотреть сообщение

А можно ещё сделать чтобы он считал в другом формате как
тут расписано?

Так это же вроде Dragokas сделал.



0



Jeka_Osokin

11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

08.01.2013, 21:13

 [ТС]

15

Dragokas сделал

Не знаю… , в общем тут так я вырезки из кода тогда приводил и по этому полностью код работает не корректно…

Windows Batch file
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
Set b=backup
Set m=mod
 
(Всякие коды...)
 
:gtada
cls
echo.
echo  Пожалуйста подождите...
set p=%u%
goto sco
 
(Всякие коды...)
 
:yefi
cls
echo.
echo                                   Установка
echo.
echo   Идёт подсчёт файлов и их размера...
set p=%u%%m%
:sco
attrib -R * /S /D
if exist %u%%m% attrib +R mod
if exist %u%%b% attrib +R backup
For /F "tokens=1-3" %%a IN ('Dir "%p%" /-C/S/A:-D-R') Do Set DirSize=!n2!& Set n2=%%c
Set DirSize=%DirSize:~0,-6%
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%p%" /-C /S /A:-D-R^|find /I "файлов"') Do (
set fi=%%a
attrib -R * /S /D
)
if errorlevel 6 (
cls
echo.
echo                             Информация GTA IV
echo  Размер %DirSize% MB
echo  Установлена по пути:
echo  %u%
goto usmd
)
cls
echo.
echo                                   Установка
echo.
echo   Найдено !fi! файлов, размер которых %DirSize% MB
echo.
echo   Начать установку
echo   Удаление мода
echo   Назад
choice /C 123 /N
if errorlevel 3 goto re
if errorlevel 2 goto ud
if errorlevel 1 goto set
:nofi
color 74
echo.
echo   Папка с модами не найдена
goto m

Когда в «главном меню» выбираю «установку» (errorlevel 2) , он мне на пол секунды показывает «переустановка атрибутов скрытого файла F:bdektop.ini не произведена» а потом показывает всё правильно… (строка 42-49) , но когда я в «главном меню» выбираю «инфо» (errorlevel 6) он мне это-же самое показывает (строка 42-49) , а мне надо чтобы при выборе «инфо» (errorlevel 6) он показывал (сторки 34-39)

Добавлено через 2 часа 9 минут
Да и ваще , тщательно по смотря я понял что он как-то не правильно показывает размер папки ,когда исключает те две…



0



Pure Free Digital Ghost

4598 / 1910 / 370

Регистрация: 06.01.2013

Сообщений: 4,564

08.01.2013, 21:27

16

Хм, странно о_0
Я по сути добавил к тем папкам атрибут «Только чтение», а затем запретил считать файлы с этим атрибутом команде ‘dir’. После чего снял этот атрибут. Странно.



0



Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

08.01.2013, 21:42

17

Jeka_Osokin, все не читал. Но ошибка «переустановка атрибутов не произведена»
бывает по 2 причинам.

1) не может получить доступ к файлу (заблокирован приложением или не хватает прав)
2) файл является скрытым или системным, тогда нужно указывать не просто -R, а -S -H -R



0



11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

09.01.2013, 01:43

 [ТС]

18

Цитата
Сообщение от FraidZZ
Посмотреть сообщение

Хм, странно о_0

Не знаю не знаю….

Цитата
Сообщение от Dragokas
Посмотреть сообщение

бывает по 2 причинам

1 доступ к файлу быть и не может , потому что файла то и нету!
2 по идее он есть токо на рабочем столе и он скрытный , но код думает что он в этой папке…



0



Dragokas

Эксперт WindowsАвтор FAQ

17954 / 7591 / 889

Регистрация: 25.12.2011

Сообщений: 11,323

Записей в блоге: 17

09.01.2013, 01:53

19

Позвольте спросить. Вот здесь Вы что пытаетесь сделать
и имеет ли это прямое отношение к названию данной темы?
Может стоит перенести в новую тему, дав определенное название.

Цитата
Сообщение от Jeka_Osokin
Посмотреть сообщение

Bash
1
2
3
For /F "skip=4 tokens=1-3" %%a IN ('Dir "%p%" /-C /S /A:-D-R^|find /I "файлов"') Do (
set fi=%%a
attrib -R * /S /D

)



0



11 / 11 / 1

Регистрация: 31.08.2012

Сообщений: 110

12.01.2013, 18:18

 [ТС]

20

Цитата
Сообщение от Dragokas
Посмотреть сообщение

Вот здесь Вы что пытаетесь сделать

Извиняюсь , попало просто под общий код , там определяется сколько файлов в папке , это не имеет отношение к данному вопросу , но главное то как заставить его не считать размер папки backup и mod?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.01.2013, 18:18

Помогаю со студенческими работами здесь

Размер папки
Всем привет! Нужно узнать развер папки! С примером пожалуйста!

Размер папки
Доброго времени суток!
Подскажите как можно узнать размер выбранного каталога?
в интернете ни…

РАЗМЕР ПАПКИ
Требуется определить размер папки на диске
Использую функции
прописаные здесь:…

Размер папки .svn
Добрый день. Использую tortoisesvn. Очень быстро растет скрытая папка .svn. Как ее можно очищать…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20



возможно ли в Windows получить размер папки из командной строки без использования какого-либо стороннего инструмента?

Я хочу тот же результат, что и при щелчке правой кнопкой мыши на папке в проводнике Windows → свойства.


669  


14  

14 ответов:

вы можете просто добавить размеры рекурсивно (ниже приведен пакетный файл):

@echo off
set size=0
for /r %%x in (folder*) do set /a size+=%%~zx
echo %size% Bytes

однако, это имеет несколько проблем, потому что cmd ограничивается 32-разрядной целочисленной арифметикой со знаком. Так что он получит размеры выше 2 гиб неправильно1. Кроме того, он, вероятно, будет подсчитывать символические ссылки и соединения несколько раз, поэтому в лучшем случае это верхняя граница, а не истинный размер (у вас будет эта проблема с любым инструментом).

альтернатива PowerShell:

Get-ChildItem -Recurse | Measure-Object -Sum Length

или короче:

ls -r | measure -s Length

если вы хотите его красивее:

switch((ls -r|measure -s Length).Sum) {
  {$_ -gt 1GB} {
    '{0:0.0} GiB' -f ($_/1GB)
    break
  }
  {$_ -gt 1MB} {
    '{0:0.0} MiB' -f ($_/1MB)
    break
  }
  {$_ -gt 1KB} {
    '{0:0.0} KiB' -f ($_/1KB)
    break
  }
  default { "$_ bytes" }
}

вы можете использовать это непосредственно с cmd:

powershell -noprofile -command "ls -r|measure -s Length"

1 у меня есть частично законченная библиотека bignum в пакетных файлах где-то, которая, по крайней мере, получает право на целочисленное сложение произвольной точности. Я должен действительно освободить его, я думаю : -)

есть встроенный инструмент Windows для этого:

dir /s 'FolderName'

это будет печатать много ненужной информации, но конец будет размер папки, как это:

 Total Files Listed:
       12468 File(s)    182,236,556 bytes

Если вам нужно включить скрытые папки добавить /a.

Я предлагаю скачать утилиту DU из пакета Sysinternals, предоставленного Microsoft по этой ссылке
http://technet.microsoft.com/en-us/sysinternals/bb896651

usage: du [-c] [-l <levels> | -n | -v] [-u] [-q] <directory>
   -c     Print output as CSV.
   -l     Specify subdirectory depth of information (default is all levels).
   -n     Do not recurse.
   -q     Quiet (no banner).
   -u     Count each instance of a hardlinked file.
   -v     Show size (in KB) of intermediate directories.


C:SysInternals>du -n d:temp

Du v1.4 - report directory disk usage
Copyright (C) 2005-2011 Mark Russinovich
Sysinternals - www.sysinternals.com

Files:        26
Directories:  14
Size:         28.873.005 bytes
Size on disk: 29.024.256 bytes

пока вы находитесь на нем, взгляните на другие утилиты. Они являются спасателем жизни для каждого профессионала Windows

Oneliner:

powershell -command "$fso = new-object -com Scripting.FileSystemObject; gci -Directory | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName | sort Size -Descending | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName"

то же самое, но только Powershell:

$fso = new-object -com Scripting.FileSystemObject
gci -Directory `
  | select @{l='Size'; e={$fso.GetFolder($_.FullName).Size}},FullName `
  | sort Size -Descending `
  | ft @{l='Size [MB]'; e={'{0:N2}    ' -f ($_.Size / 1MB)}},FullName

Это должно привести к следующему результату:

Size [MB]  FullName
---------  --------
580,08     C:myToolsmongo
434,65     C:myToolsCmder
421,64     C:myToolsmingw64
247,10     C:myToolsdotnet-rc4
218,12     C:myToolsResharperCLT
200,44     C:myToolsgit
156,07     C:myToolsdotnet
140,67     C:myToolsvscode
97,33      C:myToolsapache-jmeter-3.1
54,39      C:myToolsmongoadmin
47,89      C:myToolsPython27
35,22      C:myToolsrobomongo

Если у вас установлен git на вашем компьютере (становится все более распространенным) просто откройте MINGW32 и введите:du folder

этот код проверен. Вы можете проверить это еще раз.

@ECHO OFF
CLS
SETLOCAL
::Get a number of lines contain "File(s)" to a mytmp file in TEMP location.
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /C "File(s)" >%TEMP%mytmp
SET /P nline=<%TEMP%mytmp
SET nline=[%nline%]
::-------------------------------------
DIR /S /-C | FIND "bytes" | FIND /V "free" | FIND /N "File(s)" | FIND "%nline%" >%TEMP%mytmp1
SET /P mainline=<%TEMP%mytmp1
CALL SET size=%mainline:~29,15%
ECHO %size%
ENDLOCAL
PAUSE

Я думаю, это будет работать только в том случае, если каталог довольно статичен и его содержимое не изменяется между выполнением двух команд dir. Возможно, способ объединить это в одну команду, чтобы избежать этого, но это сработало для моей цели (я не хотел полного списка; просто резюме).

GetDirSummary.bat скрипт:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

использование:

GetDirSummary.летучая мышь c:temp

выход:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

Я рекомендую использовать https://github.com/aleksaan/diskusage утилита. Очень просто и полезно. И очень быстро.

просто введите в командную строку

diskusage.exe -path 'd:/go; d:/Books'

и получить список папок аранжировка в размере

  1.| DIR: d:/go      | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/Books   | SIZE:  14.01 Mb   | DEPTH: 1 

этот пример был выполнен в 272ms на HDD.

вы можете увеличить глубину вложенных папок для анализа, например:

diskusage.exe -path 'd:/go; d:/Books' -depth 2

и получить размеры не только для выбранных папки, но и подпапки

  1.| DIR: d:/go            | SIZE: 325.72 Mb   | DEPTH: 1 
  2.| DIR: d:/go/pkg        | SIZE: 212.88 Mb   | DEPTH: 2 
  3.| DIR: d:/go/src        | SIZE:  62.57 Mb   | DEPTH: 2 
  4.| DIR: d:/go/bin        | SIZE:  30.44 Mb   | DEPTH: 2 
  5.| DIR: d:/Books/Chess   | SIZE:  14.01 Mb   | DEPTH: 2 
  6.| DIR: d:/Books         | SIZE:  14.01 Mb   | DEPTH: 1 
  7.| DIR: d:/go/api        | SIZE:   6.41 Mb   | DEPTH: 2 
  8.| DIR: d:/go/test       | SIZE:   5.11 Mb   | DEPTH: 2 
  9.| DIR: d:/go/doc        | SIZE:   4.00 Mb   | DEPTH: 2 
 10.| DIR: d:/go/misc       | SIZE:   3.82 Mb   | DEPTH: 2 
 11.| DIR: d:/go/lib        | SIZE: 358.25 Kb   | DEPTH: 2 

* 3,5 ТБ на сервере было проверено на наличие 3m12s

Я получил du.exe С моим распределением git. Другое место может быть вышеупомянутым Microsoft или Unxutils.

как только вы получили ду.exe на вашем пути. Вот твой fileSizes.bat : -)

@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"

___________
DIRECTORIES
37M     Alps-images
12M     testfolder
_____
FILES
765K    Dobbiaco.jpg
1.0K    testfile.txt
_____
TOTAL
58M    D:picturessample

Я думаю, что ваш единственный вариант будет diruse (очень поддерживаемое решение 3rd party):

получить размер файла / каталога из командной строки

окна командной строки является unfortuntely довольно строгие, можно также установить программа который является мечтой использовать по сравнению с cmd. Это даст вам доступ к портированному инструменту Unix du, который является основой diruse на windows.

Извините, я не смог ответить на ваши вопросы напрямую с помощью команды вы можете запустить на собственном cli.

попробуй:

SET FOLDERSIZE=0
FOR /F "tokens=3" %A IN ('DIR "C:Program Files" /a /-c /s ^| FINDSTR /C:" bytes" ^| FINDSTR /V /C:" bytes free"') DO SET FOLDERSIZE=%A

изменить C:Program файлы в любую папку, которую вы хотите, и измените %A на %%A при использовании в пакетном файле

он возвращает размер всей папки, включая вложенные папки и скрытые и системные файлы, и работает с папками более 2GB

Он пишет на экране, поэтому вам придется использовать промежуточный файл, если вы этого не хотите.

Я решил аналогичную проблему. Некоторые из методов на этой странице медленны, а некоторые проблематичны в многоязычной среде (все они предполагают английский язык).
Я нашел простой обходной путь с помощью vbscript в cmd. Он испытан в W2012R2 и W7.

>%TEMP%_SFSTMP$.VBS ECHO/Set objFSO = CreateObject("Scripting.FileSystemObject"):Set objFolder = objFSO.GetFolder(%1):WScript.Echo objFolder.Size
FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%_SFSTMP$.VBS') DO (SET "S_=%%?"&&(DEL %TEMP%_SFSTMP$.VBS))

Он установил переменную окружения S_. Вы можете, конечно, изменить последнюю строку, чтобы непосредственно отобразить результат, например

FOR /F %%? IN ('CSCRIPT //NOLOGO %TEMP%_SFSTMP$.VBS') DO (ECHO "Size of %1 is %%?"&&(DEL %TEMP%_SFSTMP$.VBS))

вы можете использовать его как подпрограмму или как standlone cmd. Параметр-имя тестируемой папки, закрытой в двойные кавычки.

:: получить ряд строк, которые возвращает команда Dir (/- c для устранения разделителей чисел: . ,)
[«Tokens = 3» смотреть только на третий столбец каждой строки в Dir]

FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO set /a i=!i!+1

номер предпоследней строки, где находится количество байтов суммы файлов:

set /a line=%i%-1

наконец, получить количество байтов в предпоследней строке 3 — го столбца:

set i=0
FOR /F "tokens=3" %%a IN ('dir /-c "%folderpath%"') DO (
  set /a i=!i!+1
  set bytes=%%a
  If !i!==%line% goto :size  
)
:size
echo %bytes%

поскольку он не использует поиск слов, он не будет иметь языка проблемы.

ограничения:

  • работает только с папками размером менее 2 ГБ (cmd не обрабатывает номера более 32 бит)
  • не считывает количество байтов внутренних папок.

самый простой способ получить только общий размер-powershell, но все же ограничен тем фактом, что имена путей длиной более 260 символов не включены в общий

Понравилась статья? Поделить с друзьями:
  • Разделить диск с на два диска windows 7 программа скачать
  • Раздать вай фай с ноутбука windows 10 скачать приложение
  • Размер папки windows 10 какой должен быть
  • Разделить диск с на два диска windows 11 без потери данных
  • Раздать вай фай с ноутбука windows 10 командная строка