Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy files from directory structure but exclude a named folder

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?

like image 686
Feety Avatar asked Feb 07 '12 23:02

Feety


2 Answers

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.

like image 154
mjolinor Avatar answered Sep 29 '22 08:09

mjolinor


If we sneak a little where-object into the pipeline I think you'll get what you seek. Each object that has a property named Directory (System.IO.FileInfo) with a property named Name with a value of old will not be passed to Copy-Item.

Get-ChildItem -Path "C:\Example*" -include *.txt -Recurse | ? {-not ($_.Directory.Name -eq "old")} |  % {Copy-Item $_.fullname "C:\Destination\"}

(Untested)

like image 29
Andy Arismendi Avatar answered Sep 29 '22 06:09

Andy Arismendi