20

I need to get robocopy to exclude any file whose path contains a directory with a particular name. For example, "bar":

c:\foo\bar\a.txt
c:\bar\c.txt
d:\baz\bar\flub\d.txt

should be excluded, but not

c:\foo\barf\b.txt

Here are the things I tried -- each of which was rejected by robocopy:

/XD \bar\
/XD *\bar\*
/XD *^\bar^\*

Any ideas?

4 Answers 4

24

Turns out the /XD matches on the directory name -- not the full path. So you don't actually have to worry about matching the backslashes.

So to exclude directories (anywhere in the path) called "bar", a simple /XD bar will work. If you wanted to exclude "barf", too, you could use /XD bar*.

Sometimes the answer is simpler than you think.

5

Part of the failure is using a trailing \ in Robocopy when referring to a directory - which is a no-no - as Robocopy tries to interpret it as an escape character. Almost everyone makes this mistake in one way or another with Robocopy. With that in mind, this example will work:

/XD "\Bar"

If you wanted to match a more specific folder structure (so as not to match other subfolders, you can add more detail, like:

/XD "\Foo\Bar"
/XD "C:\Foo\Bar"
0
1

If your trying different directory filters, make sure to clear out your destination folder between changes!

A gotcha for me was that I didn't realize the ignore directory switch is applied to the destination folders as well. I had ran robocopy with /MIR and changed the source directory, and my destination directory updated as expected. Then I noticed I had archive folders I didn't want, so I added /XD archive, but my destination folder still had archive folders in it!

After messing with wildcards and including/excluding the \s, I finally tried deleting the destination folder and re-running the script - this time it didn't have the archive folders! Here is the command I was running, with the directory names changed to protect the innocent:

robocopy \\SERVER\Some\Folder\Path .\Some\Relative\Path /Copy:DAT /Mir /R:0 /W:1 /XD archive*
1

I'm sorry, but according to the documentation at https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy:

/xf <FileName>[ ...] Excludes files that match the specified names or paths. Note that FileName can include wildcard characters (* and ?).
/xd <Directory>[ ...] Excludes directories that match the specified names and paths.

So this specifically means that wildcard can be used in the /xf flag but not in the /xd flag.

1
  • Maybe there's a bug in the docs? /xd can handle wildcards (on my win11 22H2) if there's no [back]slash in the specified directory. Aug 4, 2023 at 11:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .