This is not about spaces, as others have suggested, but about the closing bracket in the environment variable ProgramFiles(x86) This makes the parser think that the block ends prematurely ( shameless self-promotion ).
The quotes really help in this case, because they make the parser jump over the entire quoted part and rightly assume that the next parenthesis is the actual closing. but the fix could be much simpler:
if Exist "%ProgramFiles(x86)%" Set TargetDir=%ProgramFiles(x86)%\My Directory Name has spaces
Why use a block in brackets in general if everything you do inserts exactly one command into it?
set itself does not need quotation marks, except when its arguments contain special characters, such as < , > , | , & , which the shell itself processes. This is not a panacea, although it makes handling user input or file contents the right pain from time to time.
Also, never put spaces around = in the set command. This will create an environment variable with its name ending in a space and its contents, starting with a space. This was partially fixed in Windows 7, quietly creating both a variable with space at the end, and without it:
> set foo = bar > set foo foo=bar foo = bar
But this did not happen in previous versions of Windows, so just do not use spaces around = unless you know what exactly you want :-)
Joey
source share