title: Why does delayed expansion fail when inside a piped block of code?
body: <p>Here is a simple batch file that demonstrates how delayed expansion fails if it is within a block that is being piped. (The failure is toward the end of the script) Can anyone explain why this is?</p>
  
  <p>I have a work-around, but it requires creation of a temporary file. I initially ran into this problem while working on <a href="https://stackoverflow.com/questions/5607489/find-files-and-sort-by-size-in-a-windows-batch-file/8192602#8192602">Find files and sort by size in a Windows batch file</a></p>
  
  <pre><code>@echo off
  setlocal enableDelayedExpansion
  
  set test1=x
  set test2=y
  set test3=z
  
  echo(
  
  echo NORMAL EXPANSION TEST
  echo Unsorted works
  (
    echo %test3%
    echo %test1%
    echo %test2%
  )
  echo(
  echo Sorted works
  (
    echo %test3%
    echo %test1%
    echo %test2%
  ) | sort
  
  echo(
  echo ---------
  echo(
  
  echo DELAYED EXPANSION TEST
  echo Unsorted works
  (
    echo !test3!
    echo !test1!
    echo !test2!
  )
  echo(
  echo Sorted fails
  (
    echo !test3!
    echo !test1!
    echo !test2!
  ) | sort
  echo(
  echo Sort workaround
  (
    echo !test3!
    echo !test1!
    echo !test2!
  )&gt;temp.txt
  sort temp.txt
  del temp.txt
  </code></pre>
  
  <p>Here are the results</p>
  
  <pre><code>NORMAL EXPANSION TEST
  Unsorted works
  z
  x
  y
  
  Sorted works
  x
  y
  z
  
  ---------
  
  DELAYED EXPANSION TEST
  Unsorted works
  z
  x
  y
  
  Sorted fails
  !test1!
  !test2!
  !test3!
  
  Sort workaround
  x
  y
  z
  </code></pre>