6

Does setlocal enabledelayedexpansion only work in a batch file? How can setlocal enabledelayedexpansion be used in a cmd prompt?

SomethingDark
  • 13,229
  • 5
  • 50
  • 55
user15964
  • 2,507
  • 2
  • 31
  • 57

2 Answers2

3

You can enable delayed expansion in a command prompt with the command cmd /V:ON

From cmd /?:

/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
SomethingDark
  • 13,229
  • 5
  • 50
  • 55
  • @user15964 - When you combine commands like that, they are all interpreted within the context of the current environment, so `command` is treated like it is still in the `/V:OFF` cmd prompt. A one-liner like you want is not possible. – SomethingDark May 15 '15 at 05:42
  • I stand corrected. (To be fair, I can't imagine a single situation where I would ever be forced to use a one-liner.) The information about the environment not changing is still good, so I won't delete the comment. – SomethingDark May 15 '15 at 07:36
  • @PetSerAl Are you sure? `cmd /v:on /c command` didn't works for me – user15964 May 15 '15 at 07:56
  • @user15964 I type `set var=value&cmd /v:on /c echo !var!` in my `cmd` prompt, and I got `value` printed, as result. – user4003407 May 15 '15 at 11:15
1

Learn by example: Copy&Paste from my CMD window:

==>echo !os! %pp%
!os! %pp%

==>cmd /E:ON /V:ON /K set "pp=yy" & set pp & echo !os! !pp!

==>echo !os! %pp%
Windows_NT yy

==>exit
Environment variable pp  not defined
!os! !pp!

==>cmd /E:ON /V:ON /K set "pp=yy" ^& set pp ^& echo !os! !pp!
pp=yy
Windows_NT yy

==>echo !os! %pp%
Windows_NT yy

==>exit

==>echo !os! %pp%
!os! %pp%

==>

Explanation:

  • echo !os! %pp% returns !os! %pp% showing delayed expansion disabled and pp variable not defined in current CLI;
  • cmd /E:ON /V:ON /K set "pp=yy" & set pp & echo !os! !pp! returns nothing, new instance of the Windows command interpreter has delayed expansion enabled (see echo !os! %pp% output);
  • exit returns result of set pp & echo !os! !pp! in a parent CLI instance: Environment variable pp not defined and !os! !pp!;
  • cmd /E:ON /V:ON /K set "pp=yy" ^& set pp ^& echo !os! !pp! returns pp=yy and Windows_NT yy in the new CLI instance (note all & escaped by ^);
  • echo !os! %pp% returns Windows_NT yy in the new CLI instance (it shows delayed expansion enabled and pp variable defined in the child CLI);
  • exit to a parent CLI instance;
  • echo !os! %pp% returns !os! %pp% again.
JosefZ
  • 28,460
  • 5
  • 44
  • 83