44

Is there a way to set environment variables for a single command on Windows like ENVVAR=abc command on Unix?

Variables set by set command on Windows seem to remain for the following commands, but this is not what I want.

2
  • I think you will have to unset them yourself.
    – Zina
    Mar 6, 2016 at 17:36
  • 2
    Not a duplicate - that other one is specific to CMD, this does not exclude powershell Apr 20, 2021 at 10:01

1 Answer 1

52

Is there a way to set environment variables for a single command?

From the current cmd shell:

You have to clear the variable yourself.

set "ENVVAR=abc" && dir & set ENVVAR=

From a batch file:

You can use setlocal and endlocal.

@echo off
setlocal 
  set "ENVVAR=abc" && dir
endlocal

Use a child cmd shell:

You can use cmd /c to create a child shell.

The variable is set in the child shell and doesn't affect the parent shell (as pointed out in a comment by jpmc26).

cmd /C "set ENVVAR=abc && dir"

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • cmd - Start a new CMD shell and (optionally) run a command/executable program.
  • endlocal - End localisation of environment changes in a batch file. Pass variables from one batch file to another.
  • redirection - Redirection operators.
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • setlocal - Set options to control the visibility of environment variables in a batch file.
5
  • 1
    Another option is to launch a separate cmd process and set them there. E.g., cmd /C "set ENVVAR=abc && dir". Since it won't affect the parent process, it will be effectively "cleared" on exit.
    – jpmc26
    Mar 6, 2016 at 19:48
  • @jpmc26 Good one. Thanks. Added to answer.
    – DavidPostill
    Mar 6, 2016 at 20:26
  • That first method won't clear the variable if the command fails.
    – nobody
    Mar 6, 2016 at 22:36
  • @AndrewMedico Thanks. Good point. Answer fixed.
    – DavidPostill
    Mar 6, 2016 at 22:53
  • 2
    Beware: This does not set ENVVAR to the string abc but to abc ! The extra space can simply be fixed by leaving it out before the &&. You might want to edit your answer, maybe even explicitly pointing out this issue because it might be surprising for unix affine people. It's extra hard to debug because output of set without any parameters when copied from a cmd.exe window does not include such trailing spaces! Apr 4, 2023 at 16:55

Not the answer you're looking for? Browse other questions tagged .