0

I need to run the command wmic csproduct get name and transfer the second line to a variable so I can append it to another variable. Most of the results I've found suggest using the below code but it seems like it relies on there being an external text file or batch script to run. Is there a way to run the command within my batch script without the need for another file?

for /f %%i in ('command') do set RESULT=%%i
echo %RESULT%
jip
  • 1

1 Answers1

0

The for loop does not process a file or external batch, it processes the Command

An example is the Choice command. You can use this method to return the actual keypress of the command:

For /F "Delims=" %%K in ('CHOICE /N /C:YN') Do Set "Key=%%K"

Which will return a value of either Y or N in the Variable Key

The typical methods of converting command output are:

For /F "Delims=" %%O in ('command') Do Set "Result=%%O"

Or

For /F "UsebackQ Tokens=* Delims=" %%O in (`"command"`) Do Set "Result=%%O"

With the method used differing depending on whether you need to isolate a specific token from the output / need to process a command with quotes.

In your particular instance, you can set the value directly to the value variable with the /format:value switch

For /F "Delims=" %%a in ('"wmic csproduct get name /format:value"') Do (Set %%a>Nul)
Echo(%name%

The >nul component is required as this would otherwise have the result of outputting all environmental variables by enacting Set

T3RR0R
  • 2,747
  • 3
  • 10
  • 25
  • I'd seen the /format switch in a few posts but it usually wasn't the subject of the question and thus wasn't explained. Thank you for going into detail on this, everything works just fine now! – jip May 07 '20 at 17:09