Save command result in a variable

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
vaschthestampede
Posts: 2
Joined: 27 Dec 2023 04:32

Save command result in a variable

#1 Post by vaschthestampede » 27 Dec 2023 04:36

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?

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Save command result in a variable

#2 Post by jeb » 27 Dec 2023 05:08

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%'

vaschthestampede
Posts: 2
Joined: 27 Dec 2023 04:32

Re: Save command result in a variable

#3 Post by vaschthestampede » 27 Dec 2023 07:56

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
	)

jeb
Expert
Posts: 1055
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Save command result in a variable

#4 Post by jeb » 28 Dec 2023 05:54

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!

Post Reply