How can I set an environment variable to the output of a command in a Windows batch file? The command will return a single value of around 32 characters (e.g. type myfile.txt).

3 Answers 3



for /f "delims=" %a in ('command to run') do @set example_environment_variable=%a


for /f "delims=" %a in ('command to run') do @setx example_environment_variable=%a

Sidenote, set sets it just for this command process/window, but setx sets it for the whole user/system.

  • Thanks. Looks like my command has parenthesis in it. I tried to escape them with backslashes, but no dice. Here's the command I'm trying to use: powershell.exe -command (Get-SSMParameter -Region us-east-1 -Name "SumoI" -WithDecryption $true).Value' ... and here's the error: ".Value') was unexpected at this time."
    – slantalpha
    Jun 8, 2019 at 3:42
  • If you have a powershell cmdlet don’t use batch file magic, do it all in powershell.
    – eckes
    Jun 8, 2019 at 3:48
  • @eckes Agreed, that's probably better. How do I concatenate the variable with running a command from Powershell? $Output = C:\MyCommand -AccessKey$MYVAR | Out-String
    – slantalpha
    Jun 8, 2019 at 5:40
  • Setx doesn't use the equals sign. Replacing it with a space is better. If there's a chance of %a having a space in it, add double quotes.
    – Jamie
    Mar 16, 2021 at 23:40

Try running these commands:

for /f "delims=" %a in ('mybatchfile.bat') do @set myenvvar=%a
echo %myenvvar%


for /f "usebackq delims==" %v in (`echo new_value`) do set new_var=%v 

Why would somebody want to use this version?

According to for /? help, one may want to use it when dealing with double quotes in the file names (as a matter of fact, that's how I ended up here):

usebackq        - specifies that the new semantics are in force,
                  where a back quoted string is executed as a
                  command and a single quoted string is a
                  literal string command and allows the use of
                  double quotes to quote file names in


Finally, you can use the FOR /F command to parse the output of a
command.  You do this by making the file-set between the
parenthesis a back quoted string.  It will be treated as a command
line, which is passed to a child CMD.EXE and the output is captured
into memory and parsed as if it was a file.  So the following

  FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i

would enumerate the environment variable names in the current

  • Why would somebody want to use this version? … … … … … … … … … … … … … … … … … … … … … … … … … … … … Please do not respond in comments; edit your answer to make it clearer and more complete. Aug 24, 2021 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.