title: The curious case of the missing exclamation mark in CMD files
body: <p>I have whittled down a more complex CMD script to the essentials. It reads an input file line by line, unquotes it (if quoted) and writes it out to another CMD file.</p>
  
  <p>The problem is that if the input file contains exclamation marks (! or bang) the character gets stripped out somewhere along the line.</p>
  
  <p>Here is the CMD script, BANG1.CMD:</p>
  
  <pre><code>@echo off
  setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
  if exist bang2.cmd del bang2.cmd
  for /f "tokens=*" %%a in (bang1.txt) do call :doit1 %%a
  exit /b
  
  :doit1
  set P1=%1
  if %P1%. EQU . exit /b
  call :unquotex P1 %P1%
  echo&gt;&gt;bang2.cmd echo P1:[%P1%]
  exit /b
  
  :unquotex
  set X=%2
  set Q=%X:~0,1%
  if "!Q!" EQU ^""" SET X=!X:~1,-1!
  set %1=%X%
  exit /b
  </code></pre>
  
  <p>Here is the input file BANG1.TXT:</p>
  
  <pre><code>HelloWorld
  "Hello World"
  Hello!World
  "Hello!World"
  </code></pre>
  
  <p>The resulting file BANG2.CMD ends up containing this:</p>
  
  <pre><code>echo P1:[HelloWorld]
  echo P1:[Hello World]
  echo P1:[HelloWorld]
  echo P1:[HelloWorld]
  </code></pre>
  
  <p>The question is, what happened to the embedded bangs?  I have tried with and without ENABLEDELAYEDEXPANSION. I have even tried escaping (^) the bangs in the input file, still with no luck.</p>
  
  <p>Is there any way to preserve them?</p>
  
  <p>Thanks.</p>