Here are two approaches:
@echo off
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%
::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%
::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set "" &::
;;set "}}==%%#"" &::
::::::::::::::::::::::::::::::::::::::::::::::::::
:: --examples
::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%
::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%
the output of the script:
1: Active code page: 65001
2: mypc\user
3: Microsoft Windows [Version 10.0.19042.1110]
4: mypc
Explanation:
1] the parts ending with &::
are end-of-line comment and can be ignored. I've put them only for macro enclosing
2] ;;
at the start of the line will be ignored as ;
is a standard delimiter for batch script. It is put there as it reminds a comment and to further enhance where the macro definitions are assigned.
3] the technique used is called 'macro' it assigns command to a variable and when the variable is invoked the command is executed.
4] the first macro defined contains two parts:
set "[[=>"#" 2>&1&set/p "
and
set "]]==<# & del /q # >nul 2>&1"
separated by &
which allows me to define them on one line. The first takes the output of a command and redirects it ot a file #
. And adds set/p
in order to start the reading the file with set /p
technique .The second macro finishes the set /p
reading with <#
and then deletes the file. The text between two macros is the name of the variable. Something like set /p myVariable=<#
5] The second macro contains three parts and expanded is just a for /f
loop. Probably can be done in a more elegant way.