Error when using BAT Files. - R was unexpected at

2019-07-29 07:21发布

问题:

This is code:

call n:\xxx\xxx\variables.bat %1 %2 %3 %4 %5 %6

set yourZipPassword=%xxx%
set yourFolderPath="n:\xxxx\xxxx\%xxxx%"

for /R "%yourFolderPath%" %%I in ("*.zip") do (
  "C:\Program Files\7-Zip\7z.exe" x -p%yourZipPassword% -y -o"%%~dpI" "%%~fI" 
)

Do not know what to do with this error - "R was unexpected at this time."

And this bat file stuck on this line and not processing anymore:

for /R "%yourFolderPath%" %%I in ("*.zip") do (

回答1:

Change the set syntax from...:

set yourFolderPath="n:\xxxx\xxxx\%xxxx%"

...to the following (in general):

set "yourFolderPath=n:\xxxx\xxxx\%xxxx%"

So the quotes are no longer part of the value. As you have it in your question, the for /R loop (for /R "%yourFolderPath%") receives a root path like for /R ""n:\xxxx\xxxx\%xxxx%"", so it is "over-quoted". This constitutes a problem particularly in case there are white-spaces and/or special characters in the variable value.


The changed set syntax has got another advantage: Imagine you have a variable holding a directory path and another one holding a file name, using the syntax from your question:

set PDIR="D:\Data"
set FILE="file.ext"

Now let us concatenate these values:

echo unquoted: %PDIR%\%FILE%
echo quoted: "%PDIR%\%FILE%"

The returned lines were:

unquoted: "D:\Data"\"file.ext"
quoted: ""D:\Data"\"file.ext""

You can see there are some disturbing quotes. Now let us use the changed syntax:

set "PDIR=D:\Data"
set "FILE=file.ext"

echo unquoted: %PDIR%\%FILE%
echo quoted: "%PDIR%\%FILE%"

So the returned lines were:

unquoted: D:\Data\file.ext
quoted: "D:\Data\file.ext"

So there are no more disturbing quotes.


Note that the changed syntax only works with command extensions enabled, but this is the default setting for the Windows command prompt cmd anyway.