Copy files from directory structure but exclude a named folder

Feety picture Feety · Feb 8, 2012 · Viewed 10k times · Source

I am looking to copy files from a directory structure over to a new folder. I am not looking to preserve the file structure, just get the files. The file structure is such that there can be nested folders, but anything in a folder named 'old' I do not want moved over.

I made a couple attempts at it, but my powershell knowledge is very limited.

Example being where the current file structure exists:

Get-ChildItem -Path "C:\Example\*" -include "*.txt -Recurse |% {Copy-Item $_.fullname "C:\Destination\"}

This gives me all the files all I want, including all the files I don't want. I do not want to include any files that are in the 'old' folder. To note: there are multiple 'old' folders. I tried -exclude, but it looks like it only pertains to the file name, and I am not sure how to -exclude on a path name, while still copying the files.

Any help?

Answer

mjolinor picture mjolinor · Feb 8, 2012

How about this:

C:\Example*" -include "*.txt -Recurse |
  ?{$_.fullname -notmatch '\\old\\'}|
    % {Copy-Item $_.fullname "C:\Destination\"}

Exclude everything that has '\old\' anywhere in it's path.