0

Given the following batch file:

@echo off
echo %programfiles(x86)%
set test=%programfiles(x86)%
echo %test%
if 0==0 ( 
    set test2=%programfiles(x86)%
)
echo %test2%

the output is returned as:

C:\Program Files (x86)
C:\Program Files (x86)
C:\Program Files (x86

Notice the missing bracket on the last line.

Can anyone explain what has happened or what I've done incorrectly?

Compo
  • 36,585
  • 5
  • 27
  • 39
Tinu
  • 23
  • 3

3 Answers3

3

When %programfiles(x86)% is expanded, it becomes C:\Program Files (x86)

Your if command becomes

if 0==0 (
    set test2=C:\Program Files (x86)
)

The parser then reads it as

if 0==0 (
    set test2=C:\Program Files (x86
)

This can be prevented with

if 0==0 (
    set "test2=%programfiles(x86)%"
)

The "" delimiters ensure that the exact string is passed as an argument to the SET command.

Input of a single ) on a line produces no error response in the CMD environment.

Tzalumen
  • 652
  • 3
  • 16
1

%programfiles(x86)% was parsed to be C:\Program Files (x86) which caused closure of your if statement (The last character of the path is ), which closed the if)

You can try adding quotation marks to indicate its a part of the string:

if 0==0 ( 
    set "test2=%programfiles(x86)%"
)
Yaniv Shaked
  • 698
  • 6
  • 12
0

The reason for missing closing parenthesis ) can be seen on modifying @echo off to @echo ON and running this batch file from within a command prompt window.

The command line with the IF condition and the entire command block starting with ( is preprocessed before executing the IF command at all to following single command line:

if 0 == 0 (set test2=C:\Program Files (x86 )

Windows command interpreter found after replacing %programfiles(x86)% by C:\Program Files (x86) during the preprocessing phase the closing parenthesis ) not inside a double quoted string. So for Windows command interpreter ) in C:\Program Files (x86) not enclosed in a double quoted string marks end of command block. The additional ) without a matching ( is simply ignored. The result is that test2 gets assigned only C:\Program Files (x86.

The solution is enclosing argument of command SET in double quotes as explained in answers on How to set environment variables with spaces? and Why is no string output with 'echo %var%' after using 'set var = text' on command line?

@echo off
echo %ProgramFiles(x86)%
set "test=%ProgramFiles(x86)%"
echo %test%
if 0 == 0 ( 
    set "test2=%ProgramFiles(x86)%"
)
echo %test2%
Mofi
  • 46,139
  • 17
  • 80
  • 143