SmplJohn
SmplJohn

Reputation: 43

Assign output of multi-line command to variable

I have a Windows batch file with command of several lines that I want to filter the output to set a variable and do some math:

@echo off
(
echo sel vol c
echo shrink querymax
echo exit
) | diskpart.exe | findstr "MB)"

That outouts:

The maximum number of reclaimable bytes is:  863 GB (884312 MB)

How can I set a variable (ie size1) just containing the number inside the ( ), and then subtract from that 20000 to make a new variable.

Like this:

set /a "size2=%size1%-20000"

Upvotes: 1

Views: 56

Answers (1)

Magoo
Magoo

Reputation: 80173

@ECHO OFF
SETLOCAL
FOR /f "tokens=2delims=(" %%e IN ('(echo sel vol c^&echo shrink querymax^&ECHO exit^) ^| diskpart.exe ^| findstr "MB)"') DO (
 FOR /f %%y IN ("%%e") DO SET "size1=%%y"
)
SET /a size2=size1-20000
SET siz
 
GOTO :EOF

The single-quoted command in the first set of parentheses should be familiar. I added exit to quite diskpart. The carets are required to tell cmd that the following symbol is part of the command-to-be-executed, not of the for. This is termed escaping those characters and the escape character is ^.

So the output if the diskpart command is filtered by the findstr and we pick the second token from the line using ( as the delimiter. (See for /? for documentation (or thousands of examples on SO)

%%e then gets anumber MB) assigned to it, so is again tokenised by for/f as a string, thos time picking the default first token and using the default delimiter set, which includes Space and assigning to %%y thence to size1.

Upvotes: 2

Related Questions