0

every day I get files from a company directory and I'm automating this ... but the directory name contains a special character "&" and the scripts I have assembled do not recognize...

@Echo Off
Set _Source=C:\Users\Rafae\Desktop\test&test
Set _Dest=C:\Users\Rafae\Desktop\study
Forfiles /D +0 /P %_Source% /C "cmd /c XCopy %_Dest%"
pause

Error: 'test' is not recognized as an internal command or external, an operable program or a batch file. ERROR: The specified directory does not exist. Press any key to continue. . .

Is there a way to make cmd recognize a folder that contains "&" in the name?

  • 2
    Open a [command prompt](https://www.howtogeek.com/235101/), run `cmd /?` and read the output usage help of the Windows command processor carefully and completely from top of first to bottom of last page. There is explained when a file name or any other argument string __must__ be enclosed in `"` to get the characters with special meaning for `cmd.exe` interpreted as literal characters with the exception of `%` and `!` on enabled delayed expansion. – Mofi Apr 06 '21 at 13:13
  • 2
    See also [How does the Windows Command Interpreter (CMD.EXE) parse scripts?](https://stackoverflow.com/questions/4094699/) and [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/a/26388460/3074564) and last [Single line with multiple commands using Windows batch file](https://stackoverflow.com/a/25344009/3074564) explaining how `&` is interpreted if not being inside a double quoted argument string. – Mofi Apr 06 '21 at 13:15
  • 2
    I suggest to use as second line `Set "_Source=C:\Users\Rafae\Desktop\test&test"` and as third line `Set "_Dest=C:\Users\Rafae\Desktop\study"`and as fourth line `%SystemRoot%\System32\forfiles.exe /P "%_Source%" /C "%SystemRoot%\System32\xcopy.exe @path \"%_Dest%\\""`. But I do not really understand why you use deprecated `forfiles` and `xcopy` instead of `%SystemRoot%\System32\robocopy.exe` which would make the file copying task much easier to code and much more efficient on execution. Run in the command prompt window `robocopy /?` for help on this command. – Mofi Apr 06 '21 at 13:22
  • Thanks, I put it in quotes and it worked. – Rafael Felipe Santos Apr 06 '21 at 16:32

1 Answers1

0

You need to escape the & character, because it has a special meaning.

You can escape it with a caret character, like Set _Source=C:\Users\Rafae\Desktop\test^&test

Or with quotes

Set "_Source=C:\Users\Rafae\Desktop\test&test"

In this case, I use the extended SET syntax, the opening quote is befor the variable name, this escapes the string, but does not add the quotes to the variable.

If you use such a variable, you should always quote the result, like

Forfiles /D +0 /P "%_Source%" ...
jeb
  • 78,592
  • 17
  • 171
  • 225