Set a path variable with spaces in the path in a Windows .cmd file or batch file

Viewed 462522

I'm new to script writing and can't get this one to work. I could if I moved the files to a path without a space in it, but I'd like it to work with the space if it could.

I want to extract a bunch of Office updates to a folder with a .cmd file. To make the batch file usable on any computer, I set a path variable which I only have to change in one place to run it on another machine. The problem is that the path has a space in it. If I put quotes around the path in the definition, cmd.exe puts them around the path before it appends the filename and switches and the batch fails with "Command line syntax error." Without quotes, it fails with, "is not recognized as an internal or external command, operable program, or batch file."

For testing, I'm using the help switch until or if I can get it working. I can do it using an 8.3 file/folder name (e.g. My Documents as MyDocu~1), but can it be done a different way?

10 Answers

I had this same problem recently, imagine...

Folder
  └  File1.txt
  └  File2.txt

Issue

You're right, if you add " " around the path...

SET RootFolder="C:\Folder with spaces"

it then makes it unusable if you want to then append filenames, etc (without doing some interim processing on the string...

FOR %%F IN * DO (COPY %%F "%RootFolder%\%%F")

❌ COPY File1.txt ""C:\Folder with spaces"\File1.txt"
❌ COPY File2.txt ""C:\Folder with spaces"\File2.txt"

Solution

The key is to still use " ", but put them around the entire SET statement (i.e. BEFORE the variable name)

SET "RootFolder=C:\Folder with spaces"

This will them work when you need to re-use the variable

FOR %%F IN * DO (COPY %%F "%RootFolder%\%%F")

✅ COPY File1.txt "C:\Folder with spaces\File1.txt"
✅ COPY File1.txt "C:\Folder with spaces\File2.txt"

also just try adding double slashes like this works for me only

set dir="C:\\\1. Some Folder\\\Some Other Folder\\\Just Because"

@echo on
MKDIR %dir%

OMG after posting they removed the second \ in my post so if you open my comment and it shows three you should read them as two......

Related