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

I don’t know how to describe exactly what I'm trying to do, but here is an example of a batch file that demonstrates something that I cannot understand.

I have a batch file. Inside this batch file, I am 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 does not work on line 4 Set TargetDir =... using

 \My was unexpected at this time 

I guess this is because I have spaces in my path name. I thought I could just bind 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% now wrapped in quotation marks. md "%TargetDir%"\NewSubFolder

Could this be fixed or should I just write VBScript to sort things?

+6
cmd batch-file windows-console
source share
2 answers

Just put your expression in quotation marks as follows:

 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 inside the quotation marks, and if it also has spaces, it will need to be quoted.

Now you can quote it to complete your operation:

 md "%TargetDir%\NewSubFolder" 
+6
source share

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 :-)

+2
source share

All Articles