How do I set an environment variable to a value with spaces in a batch file?

BobTheBuilder picture BobTheBuilder · Nov 7, 2009 · Viewed 13.8k times · Source

I don't know how to describe exactly what I'm trying to do but here's an example batch file that demonstrates what I can't figure out.:

I've got a batch file. Inside that batch file I'm trying to create a directory:

Set CopyFrom = %~dp0

if Exist "%ProgramFiles(x86)" (
  Set TargetDir = %ProgramFiles(x86)%\My Directory Name has spaces
)

md %TargetDir%\NewSubFolder
copy %CopyFrom%\SourceFile.zip %TargetDir%\NewSubFolder

My batch file is failing on line 4 Set TargetDir =... with:

\My was unexpected at this time

I'm assuming this is because I have spaces in my path name. I thought I could just wrap my variable with quotes:

Set TargetDir = "%ProgramFiles(x86)%\My Directory Name has spaces"

But then when I get to the line that creates the directory it fails because %TargetDir% is now wrapped in quotes. md "%TargetDir%"\NewSubFolder

Can this be fixed or should I just write a VBScript to sort things out?

Answer

zdan picture zdan · Nov 7, 2009

Just put your expression in quotes like this:

C:\>Set "TargetDir=%ProgramFiles%\My Directory Name has spaces"
C:\>echo %TargetDir%
C:\Program Files\My Directory Name has spaces

Note: It will expand the variable within the quotes, and if it too has spaces, it will need to be quoted.

Now you can quote it to perform your operation:

md "%TargetDir%\NewSubFolder"