A.D.
A.D.

Reputation: 4614

cmd: echo is not working in one-liner

I'm rewriting batch file for counting page file usage to the one-liner:

@ECHO OFF
for /f "tokens=1,2 skip=2 delims==" %%a in ('wmic pagefile list /format:list') do (
IF "%%a"=="AllocatedBaseSize" SET TOTAL=%%b
IF "%%a"=="CurrentUsage" SET USAGE=%%b
)
SET TOTAL
SET USAGE
set /a perc = 100 * USAGE / TOTAL
echo used: %perc%%%

----- OUTPUT -----

TOTAL=4095
USAGE=728
used: 17%

So far I was able to mimic it with:

(for /f "tokens=1,2 skip=2 delims==" %a in ('wmic pagefile list /format:list') do @(IF "%a"=="AllocatedBaseSize" (SET TOTAL=%b) ELSE (IF "%a"=="CurrentUsage" SET USAGE=%b)))  & SET TOTAL & SET USAGE & set /A perc=100*USAGE/TOTAL & echo|set /p dummy=% of usage

----- OUTPUT -----
TOTAL=4095
USAGE=724
17% of usage

But only because I'm using very ugly hack echo|set /p dummy=% of usage. My problem is when I tried just echo %perc%% it will print %perc%%. So now I'm just appending "of usage" to set /A's output - first because it seems that it's not possible to omit this output according to documentation set /?:

If SET /A is executed from the command line outside of a command script, then it displays the final value of the expression.

and second because I can not print the value of perc variable.

For clarity my problem can be simplified to:

C:\>set x=1 & echo %x%
%x%
C:\>echo %x%
1

Any help / explanation is welcomed.

Tried SetX variable value also.

Upvotes: 0

Views: 508

Answers (2)

MC ND
MC ND

Reputation: 70923

cmd /v:on /c "for /f "skip=2 tokens=2,3 delims=," %a in ('wmic pagefile get allocatedbasesize^,currentusage^,status /format:csv') do @(set /a "pct=%b*100/%a">nul & echo total: %a & echo usage: %b & echo used : !pct!^%)"

Upvotes: 1

Mofi
Mofi

Reputation: 49086

Change the line

set x=1 & echo %x%

to

setlocal EnableDelayedExpansion
set "x=1" & echo !x!

and command echo outputs 1 as expected.

cmd.exe replaces all references to environment variables already by their current value before executing a line or a block enclosed in parentheses. Therefore it is necessary to use delayed environment variable expansion enabled with setlocal EnableDelayedExpansion and using ! instead of % around the variable reference in this case where the variable value is modified/set on same line respectively in same block.

And use double quotes around variable=value as demonstrated here. Another example:

set /A "perc=100*USAGE/TOTAL"

Upvotes: 1

Related Questions