Reputation: 13
I'm trying to get the total size of a directory (_sourceFolder
) (including subdirectories) into one variable (_localvar
) with the code below.
I tried to enable setlocal enabledelayedexpansion
but it didn't help.
@echo off
set _sourceFolder="D:\data"
dir/A-D /S %_sourceFolder%|for /F "tokens=*" %%a in ('FIND "bytes"') do set _localvar=%%a
echo %_localvar%
However the subcommand set _localvar=%%a
is not performed, instead I see in the stdout
some output like:
C:\>set _localvar=1 File(s) 27.686 bytes
C:\>set _localvar=1 File(s) 27.686 bytes
C:\>set _localvar=3272 File(s) 1.812.083.061 bytes
C:\>set _localvar=1 File(s) 27.686 bytes
C:\>set _localvar=3275 File(s) 1.812.166.119 bytes
C:\>set _localvar=0 Dir(s) 7.431.806.976 bytes free
But %_localvar%
is still empty/not set. I expect to have %_localvar%
filled/set as displayed by the output on stdout
.
Does anybody see the error I made here?
Upvotes: 1
Views: 75
Reputation: 16226
If what you are seeking is the sum of all file sizes, this is a bit more straightforward. It does not depend on parsing the output of the DIR
command text.
FOR /F %%a IN ('powershell -NoLogo -NoProfile -Command ^
"(Get-ChildItem -File -Recurse |" ^
"Measure-Object -Sum -Property Length).Sum"') DO (SET "_localvar=%%a")
ECHO %_localvar%
Upvotes: 0
Reputation: 34899
The pipe (|
) initiates two new cmd
instances for either side, so any environment changes (like variables) are not transferred to the hosting cmd
instance.
Move the dir
command line into the set of for /F
, like this:
for /F "tokens=*" %%a in ('dir /A-D /S "%_sourceFolder%" ^| find "bytes" ^| find /V "free"') do set _localvar=%%a
Note that the pipe is escaped here (like ^|
) in order to hide it from the hosting cmd
instance, so it becomes executed in the cmd
instance that is created by for /F
. The variable assignment though is no longer involved in a pipe, therefore the assigned value is finally going to be available.
I added another filter (find /V "free"
) since I assume you do not want to capture the final "bytes free" line but the one before.
Upvotes: 3