How to turn the output of a command into a variable in CMD?

Asked

Viewed 22,737 times

11

Hello, since I started researching about these commands of CMD, this doubt about how to turn the output of a command into a variable has been the one that took me the most time.

I saw a lot of codes out there, many of them quoted that the command FOR could be used in that, but I don’t know how to use that command yet, I don’t understand its logic and even if someone could explain it to me, I would really appreciate it.

Well, the code with which I was able to redirect the output of a command to a variable.

mountvol %SystemDrive% /l >0 && set /p abc=<0

With this command I finally managed to redirect the output of Mountvol direct to a variable, indeed direct no, I believe that the data STDOUT were first directed to STDIN (with the >0 ) and then yes were used to define the variable. I’m not sure about this because although I stayed two days to get to this code, some rules of these commands are still unclear to me.

For example, for all I read about the redirectors and transponders, I shouldn’t have to put the 0 (zero) after input redirect ( < ), even so if you do not use it the command does not work.

Also there is a limitation in this code that I wanted to be able to bypass, the limitation is on the line breaks that various command outputs have. It seems not possible to define values of variables with line breaks, someone could help in this limitation?

For example, the output of the command below that would have a line break right at the beginning, could not be set as the value of the variable %abc%.

reg query HKLM >0 && set /p abc=<0

Only the outputs that did not have any line breaks could be fully set as the value of a variable, I think we can get around this with some command that changes the text formatting.

someone can help improve it?

Updating

For information I’m using a file .BAT.

I made this post because I believe that transforming the output of a command into a variable is a good way to store the information obtained from this command. Once information has become a variable, you can query it, use it in conjunction with another command, change it and more.

Below is a piece what I’m doing here, you can see I’ve rerouted the output data from mountvol for the variable %guid%, then adjusted this data to define the parameter of another command. This enables the System Protection on the partition where the online system is installed, do not perform this unless you understand that these data will erase those that already define your current settings. In this case the codes are for a .BAT.

@echo off
::
set chv=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SPP\Clients
set vlr={09F7EDC5-294E-4180-AF6A-FB0E6A0E9513}
set tip=REG_MULTI_SZ
::
mountvol %SystemDrive% /l >0 && set /p guid=<0
::
reg add "%chv%" /v "%vlr%" /t %tip% /d "%guid: =%:(%SystemDrive:~,1%%%3A)" /f && cls && echo    Comando executado com sucesso! && goto fim
::
cls
echo    Houve algum erro, execute novamente como Administrador.
::
:fim
pause>nul
exit  

I can then turn the first line of an output into a variable (if any) and modify its characters using offset (~) or assignment (=), as it is possible to see above, but the ideal would be to be able to modify the characters of the entire output and not just the first line.

Correction

I made a mistake, guys, I’m not able to redirect the data from STDOUT for STDIN as I mentioned before, this is impossible for me yet, what I was doing was redirecting STDOUT to a file without named extension 0 (zero) that was created inside the folder System32 (directory of CMD).
It turns out that because of my misinterpretation of what I read here, I really thought I was redirecting to STDIN, that is represented by a zero, but it was worth the information.
You can test and confirm this, type the following command at the prompt and you will see that actually the data STDOUT of the first command are passed to the file 02825 which will be created in System32, if the first command is correctly executed the file 02825 will be opened by Notepad, showing the output STDOUT of the first command.

reg query HKLM >02825 && notepad 02825

You can see the file 02825 by Explorer with command Explorer /select,02825 and to exclude it can use del 02825.
No news then, unless we now know that we do not need to record the output in a file with exactly extension, as a .txt.

  • Windows command prompt is quite limited compared to Windows Powershell. Have you tried to find out if you can do what you need using Powershell? http://technet.microsoft.com/pt-br/Library/bb978526.aspx

  • I’ve heard of that Powershell but I’ve never used it, so far I’m trying to CMD same war craft... as I mentioned not even know basic commands like the FOR still, I’m crawling in it.

  • Since you’re just getting started, start with the best ;-)

  • I extended my comment a little in a reply. Good luck!

5 answers

7

One option is to use Windows Powershell, which can be seen as a more modern and powerful Windows command prompt (cmd)).

Example

To set the output of the command in a variable mountvol, passing parameters to this command (in this case, I passed the parameter /?):

PS C:\Users\caffé> $mountVolHelp = mountvol /?

Now, to see the contents of the variable $mountVolHelp, with all text including line breaks, just type your name:

PS C:\Users\caffé> $mountVolHelp
Cria, exclui ou lista um ponto de montagem de volume.

MOUNTVOL [unidade:]caminho NomeVolume
MOUNTVOL [unidade:]caminho /D
MOUNTVOL [unidade:]caminho /L
MOUNTVOL [unidade:]caminho /P
                            ...
    caminho     Especifica a pasta NTFS existente onde residirá o ponto de
                montagem.
    NomeVolume  Especifica o nome de volume que é o destino do ponto de
                montagem.
    /D          Remove o ponto de montagem do volume da pasta especificada.
    /L          Lista o nome do volume montado para a pasta especificada.
                            ...
    /R          Remove pastas e configurações do Registro de pontos de
                montagem de volume que não estão mais no sistema.
    /N          Desativa a montagem automática de novos volumes.
    /E          Reativa a montagem automática de novos volumes.
                            ...

An example loop in Powershell

The code below prints the contents of $mountVolHelp adding the text "Will! " at the beginning of each line:

foreach ($linha in $mountvolHelp) {"Rá! " + $linha}

As in the for each of various programming languages, in the above code the variable $linha is created within the loop itself and at each iteration receives the value of a row of the variable $mountvolHelp, which in this context is treated as a list of lines.

Another example of using for each

PS C:\Users\caffé> foreach ($numero in 1,2,3) {$numero}
1
2
3

In the above example, "1,2,3" was treated by for each as a list of numbers.

Powershell reading example of Windows environment variables

To read %Userprofile%, for example, one of the ways is:

PS C:\Users\caffé> $env:UserProfile
C:\Users\caffé

The second line of the above code is output of the command. To assign the value of this environment variable to another variable in Powershell:

PS C:\Users\caffé> $UserProfile = $env:UserProfile

Now the variable $UserProfile contains "C: Users Caffé".

Completion

With Windows Powershell you can do everything you do with "cmd", only easier, with more features and more documentation.

To open Windows Powersheel, just press the "windows" key and type "powershell", will be shown a shortcut to the "Windows Powershell", which at first glance looks a lot like the "cmd". Another option is to type "powershell" in the "cmd" itself. Immediately a "PS" will appear at the beginning of the command prompt line, indicating that you are now in Powershell.

  • I’m looking at it now, I set $abc=reg query HKLM and that $abc has already received all the output of reg query command effortlessly, very interesting, then I used the redirector ( > ) and sent to a text file as in CMD, the difference is that this variable of the Powershell really can receive several lines, very good. I’ll keep digging here... I noticed that the variables like %Systemdrive% or %Userprofile% do not work in it, how can I get these paths ? I tried $Systemdrive$ and others but I still haven’t managed, anyway thank you so much for this.

  • @Unantec I’m glad you’re excited about this feature. It’s really another universe in relation to cmd. I updated my answer with an example of how to read Windows environment variables.

  • 2

    +1 for recommending powershell.

5

Two simple ways:

aplicacaoOuComando arg0 arg1 > temp.txt
set /p VAR=<temp.txt

another:

for /f %%i in ('aplicacaoOuComando arg0 arg1') do set VAR=%%i

EDITION

The command for /f is a parse of files. Theoretically speaking, if you pass a command, it sends the STDOUT for the input of this parse.

  • Only by complementing, even if the output has line breaks, this way it should be possible to take the whole text and put in the variable. I don’t know if you’re using it in an application or in batch-only commands.

  • That code set /p VAR=<temp.txt suffers from the same limitation as the code I used, the difference being that it creates a file on disk while my code redirects the output of the command ( STDOUT ) to the entrance ( STDIN ).Already the command FOR that you used I do not understand precisely because I never read a clear explanation about this command, I keep trying to understand what the hell is this /f or that in or that of delims= which also appears from time to time. I have never read a clear explanation about this command so I still don’t understand how it works. Thank you.

  • 1

    @Unantec I also added an example of FOR for Powershell. I’ll stop otherwise it turns into a tutorial.

  • @Unantec sorry to ask, but which language are you calling this command? Is there no other way to get the output without setting a variable and then get the result from it?

0

An option for save the command variable via looping for :

@echo off && setlocal enabledelayedexpansion
::
set "chv=HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SPP\Clients"
set "vlr={09F7EDC5-294E-4180-AF6A-FB0E6A0E9513}
set "tip=REG_MULTI_SZ"
::
for /f "tokens=*" %%i in ('mountvol %%SystemDrive%% /l') do set "guid=%%i"
:: 
rem :: use echo/ para verificar o seu comando com as variaveis:
echo/reg add "!chv!" /f /v "!vlr!" /t !tip! /d "!guid!:%SystemDrive:~,1%%%3A" && goto :zOk: || goto :nOk:

:zOk:
echo/    Comando executado com sucesso^^! & goto :eof

:nOk:
echo/    Houve algum erro, execute novamente como Administrador.^^! & timeout /t -1 >nul & goto :eof

0

Hello. I got in BAT file! This forum was very helpful, thanks to the participants.

Based on the information in this forum, I was able to make a small sequence of commands that saves the first line from the output of a command in a variable. Stayed like this:

"COMANDO QUE TENHA SAÍDA" > VARtemp.txt
set /p SuaVariavel=<VARtemp.txt
DEL VARtemp.txt

Depending on your command the output can contain multiple lines, tabs and characters. This method will save to "Sweaty" only the first line, which depending may be empty, no information.

If necessary, the contents of the file can be edited "Vartemp.txt" through commands such as the FIND so that you can only have the content you want.

Open the Output File "Vartemp.txt" and analyze its contents to study the most effective method for editing it through commands and extract only the content you want for your variable.

In my case, I just needed to know if there was a certain character in my output to the file Vartemp.txt. I used the following command:

"COMANDO QUE TENHA SAÍDA" > VARtemp.txt

FIND /i "CARACTERE" "VARtemp.txt"
if NOT %ERRORLEVEL% EQU 0 ( 
  set /p SuaVariavel= "EXISTE O CARACTERE"
  DEL "VARtemp.txt"
  GOTO INICIO
)
set /p SuaVariavel= "NÃO EXISTE O CARACTERE"

:INICIO
REM ### Continuação do script BAT ###

Good luck and good work.

Att

Thiago Morais

-1

Probably the set is changing the variable The && command has the line break rule to call another command.

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.