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

9

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

I've seen many codes out there, many quoted that the FOR command could be used in this, but I do not know how to use this command yet, I did not understand its logic and even if someone could explain it to me I would 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 directly to a variable, not directly direct, I believe the STDOUT data was first directed to STDIN (with > 0 ) and then they were used to define the variable. I'm not sure why even though I've stayed two days to get into this code, some rules of those commands are still obscure for me.

For example, for all I read about redirectors and identifiers, I should not have to put 0 (zero) after the input redirector ), even so if you do not use it the command does not work.

In addition there is a limitation in this code that I wanted to be able to work around, the limitation is on the line breaks that multiple command outputs have. It seems that it is not possible to define variable values with line breaks, could anyone help with this limitation?

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

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

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

Can anyone help improve this?

Update

For information I'm using a .BAT file.

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

Below is a piece of what I'm doing here, you can see that I redirected the output data from mountvol to the %guid% variable, then I set that data to set the other command. This enables System Protection on the partition where the online system is installed, do not run this unless you understand that this data will delete 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 transform the first line of an output into a variable (if it exists) and modify its characters using the ~ ) or assignment ( = ), as you can see above, but the ideal would be to be able to modify the characters of the whole output and not only those of the first line.

Correction

I was wrong, I am not able to redirect the STDOUT data to STDIN as I mentioned before, this is impossible for me yet, what I was doing was redirect STDOUT directory for a file without extension named 0 (zero) that was created inside the System32 ). It turns out that for my misinterpretation of what I read > here , I even thought I was redirecting to STDIN , which is represented by a zero, but worth the info. You can test and confirm this by typing the following command at the prompt and you will see that the STDOUT data of the first command is actually passed to the 02825 file that will be created in < If the first command is executed correctly, the 02825 file will open through Notepad, showing the STDOUT output of the first command.

reg query HKLM >02825 && notepad 02825

You can see the file 02825 by Explorer with the command Explorer /select,02825 and to delete it you can use del 02825 . No news then, unless we now know we do not need to write the output to a file with an extension exactly like a .txt .

    
asked by anonymous 26.11.2014 / 15:19

4 answers

5

One option is to use Windows PowerShell , which can be viewed as a command prompt of Windows (cmd) more modern and powerful (although it is even more than that).

Example

To set the output of the command mountvol in a variable, 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 $mountVolHelp variable, with all text including line breaks, just enter its 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 by adding the text "Ra!" 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 inside the loop itself and at each iteration it receives the value of a line 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 example above, "1,2,3" was treated by for each as a list of numbers.

Example of reading in Windows environment variables PowerShell

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

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

The second line of the code above is output from 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é ".

Conclusion

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", it will be shown a shortcut to "Windows PowerShell", which at first looks very much like "cmd". Another option is to type "powershell" in the "cmd" itself. You will immediately see a "PS" at the beginning of the command prompt line, indicating that you are now in PowerShell.

    
26.11.2014 / 16:24
5

Two simple ways:

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

other:

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

EDITION

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

    
26.11.2014 / 16:56
0

Hello. I got a BAT file! This forum was very helpful, thank you to the participants.

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

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

Depending on your command, the output may contain multiple lines, tabs, and characters. This method will write to "YourVariable" only the first line, which depending on it may be empty, without information.

If you need to edit the contents of the VARtemp.txt file with commands such as FIND so that you can only have the content you want.

Open the VARtemp.txt output file and analyze your content to study the most effective method for editing it via 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 for the VARtemp.txt file. 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

    
27.10.2015 / 15:34
0

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

I hope I have helped

    
05.11.2015 / 11:50