batch-filemoverobocopy

How to use ROBOCOPY to move files with % in the file name?


I try to move files based on the file name from one location to another. It seems as if Robocopy can't handle certain characters. Files with '%' in the file name are not moved.

For example I have a file a%b.xlsx in D:\test and want to move it to D:\backup.

My script:

@echo off
chcp 65001
ROBOCOPY "D:\test" "D:\backup" "a%b.xlsx" /MOVE

The file is not moved. If I replace % with %% in my script it works:

@echo off
chcp 65001
ROBOCOPY "D:\test" "D:\backup" "a%%b.xlsx" /MOVE

My questions:

  1. Is there another way to do this or is there a bug in the script?
  2. How do I know which characters need to be adjusted and how?

Solution

  • The issue arises because % is a special character in batch scripts, used for variable expansion. To use it literally in filenames, you need to escape it by doubling it (%%). This is not a bug, but expected behavior in batch scripting.

    To handle this more generally:

    1. Use double percent signs (%%) for any file containing % in its name.
    2. For other special characters (like &, |, ^), enclose the filename in quotes.
    3. Alternatively, use PowerShell instead of batch, which handles special characters better.

    Example PowerShell command:

    Move-Item "D:\test\a%b.xlsx" "D:\backup"
    

    This approach will work for files with various special characters without needing to escape them individually.

    Please if you do not understand something reach me.