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).



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 '19 at 3:42
  • If you have a powershell cmdlet don’t use batch file magic, do it all in powershell. – eckes Jun 8 '19 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 '19 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 at 23:40

Try running these commands:

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

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.