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
Try running these commands:
for /f "delims=" %a in ('mybatchfile.bat') do @set myenvvar=%a
echo %myenvvar%
Temporarily:
for /f "delims=" %a in ('command to run') do @set example_environment_variable=%a
Permanently:
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." Jun 8, 2019 at 3:42
-
If you have a powershell cmdlet don’t use batch file magic, do it all in powershell.– eckesJun 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 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.– JamieMar 16, 2021 at 23:40
Alternatively:
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
file-set.
[...]
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
example:
FOR /F "usebackq delims==" %i IN (`set`) DO @echo %i
would enumerate the environment variable names in the current
environment.