windows - Strange error in batch file when handling a file path with Program Files (x86) -


i writing batch script remove quotes java_home env variable , getting error when java_home set "program files (x86)" in path. java_home variable set c:\program files (x86)\java\jdk1.7.0_79(no quotes in value)

    set lastchar=%java_home:~-1%     set firstchar=%java_home:~0,1%      echo begin     if '^%firstchar%=='^" (         echo java_home starts quote          if '^%lastchar%=='^" (             echo java_home ends quote             set java_home=%java_home:~1,-1%    ###error occurs on line         )     )     echo end 

the output is:

 begin  \java\jdk1.7.0_7 unexpected @ time. 

as can see, none of lines after "echo begin" run. if comment out line set java_home=%java_home:~1,-1% program runs way end. also, if change java_home env var c:\program files\java\jdk1.7.0_79, script runs fine without commenting out line.

why 1 line giving me error?

the simplest way deal problematic characters within environment variables use delayed expansion. can string substitution remove quotes. assuming want modified value persist after batch script ends, use variable transfer modified value across endlocal barrier.

@echo off setlocal enabledelayedexpansion set "val=!java_home:"=!" /f "delims=" %%a in ("!val!") endlocal&set "java_home=%%a" 

it possible command line, without using batch. bit tricky proper escape sequences

for /f "delims=" %a in ('cmd /v:on /c echo !java_home:^"^=!') @set "java_home=%a"