user15964
user15964

Reputation: 2639

Using "setlocal enabledelayedexpansion" in cmd prompt

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

Upvotes: 6

Views: 2374

Answers (2)

JosefZ
JosefZ

Reputation: 30113

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.

Upvotes: 1

SomethingDark
SomethingDark

Reputation: 14305

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.

Upvotes: 4

Related Questions