Page 1 of 1

Save command result in a variable

Posted: 27 Dec 2023 04:36
by vaschthestampede
Hi everyone, I'm new here and I hope I find myself well.

Trying to automate processes I have difficulty saving the result of a command in a variable.
The only way I've found is to save it to a file first and then load it:

Code: Select all

dism /Online /Get-Capabilities | findstr "OpenSSH.Server" > AAA.txt
set /p AAA=<AAA.txt
del risultato.txt
Is there any way that doesn't involve saving files?

Re: Save command result in a variable

Posted: 27 Dec 2023 05:08
by jeb
Hi vaschthestampede,

the "normal" way is to use the FOR /F command.

Code: Select all

for /F "delims=" %%A in ('VER') do set "output=%%A"
echo output is '%output%'
But the part `set output=%%A` is called for each line of the output, therefore only the last line is stored.

In your case you should get only one line by using the findstr, but here the pipe has to be escaped.

Code: Select all

for /F "delims=" %%A in ('dism /Online /Get-Capabilities ^| findstr "OpenSSH.Server"') do set "output=%%A"
echo output is '%output%'

Re: Save command result in a variable

Posted: 27 Dec 2023 07:56
by vaschthestampede
This worked for me:

Code: Select all

for /f "delims=" %%a in (
	'dism /Online /Get-Capabilities ^| findstr "OpenSSH.Server"'
	) do (
	set output=%%a
	)
Thank you so much.

In case you need more lines this actually returns only the last line.
To avoid this I also tried concatenation but the variable is not updated.
Like this:

Code: Select all

output=""
for /f "delims=" %%a in (
	'dism /Online /Get-Capabilities ^| findstr "OpenSSH.Server"'
	) do (
	set output=%output%%%a
	)

Re: Save command result in a variable

Posted: 28 Dec 2023 05:54
by jeb
It fails because percent expansion is evaluated before a code block is executed.
Therefore you need delayed expansion here.

Code: Select all

setlocal EnableDelayedExpansion
set "output="
for /f "delims=" %%a in (
	'dism /Online /Get-Capabilities ^| findstr "OpenSSH.Server"'
	) do (
	set "output=!output!%%a"
)
echo !output!