20
8
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.
20
8
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.
28
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"
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 – 2016-03-06T19:48:40.763
@jpmc26 Good one. Thanks. Added to answer. – DavidPostill – 2016-03-06T20:26:10.477
That first method won't clear the variable if the command fails. – nobody – 2016-03-06T22:36:02.253
@AndrewMedico Thanks. Good point. Answer fixed. – DavidPostill – 2016-03-06T22:53:02.320
I think you will have to unset them yourself. – Zina – 2016-03-06T17:36:01.710