Dealing with quotes in Windows batch scripts Dealing with quotes in Windows batch scripts windows windows

Dealing with quotes in Windows batch scripts


set "myvar=c:\my music & videos"

Notice the quotes start before myvar. It's actually that simple.Side note: myvar can't be echoed afterwards unless it's wrapped in quotes because & will be read as a command separator, but it'll still work as a path.

http://ss64.com/nt/set.html under "Variable names can include Spaces"


This is the correct way to do it:

set "myvar=c:\my music & videos"

The quotes will not be included in the variable value.


It depends on how you want to use the variable. If you just want to use the value of the variable without the quotes you can use either delayed expansion and string substitution, or the for command:

@echo OFFSETLOCAL enabledelayedexpansionset myvar="C:\my music & videos"

As andynormancx states, the quotes are needed since the string contains the &. Or you can escape it with the ^, but I think the quotes are a little cleaner.

If you use delayed expansion with string substitution, you get the value of the variable without the quotes:

@echo !myvar:"=!>>> C:\my music & videos

You can also use the for command:

for /f "tokens=* delims=" %%P in (%myvar%) do (    @echo %%P)>>> C:\my music & videos

However, if you want to use the variable in a command, you must use the quoted value or enclose the value of the variable in quotes:

  1. Using string substitution and delayed expansion to use value of the variable without quotes, but use the variable in a command:

    @echo OFFSETLOCAL enabledelayedexpansionset myvar="C:\my music & videos"md %myvar%@echo !myvar:"=! created.
  2. Using the for command to use the value of the variable without quotes, but you'll have to surround the variable with quotes when using it in commands:

    @echo OFFset myvar="C:\my music & videos"for /f "tokens=* delims=" %%P in (%myvar%) do (    md "%%P"    @echo %%P created.)

Long story short, there's really no clean way to use a path or filename that contains embedded spaces and/or &s in a batch file.