Copy files from directory structure but exclude named folder

I want to copy files from a directory structure to a new folder. I do not want to save the file structure, I just get the files. The file structure is such that there may be subfolders, but I don’t want to move anything in the folder with the name "old".

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

An example where an existing file structure exists:

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

This gives me all the files that I want, including all the files that I do not want. I do not want to include files in the "old" folder. It should be noted: there are several "old" folders. I tried -exclude, but it looks like this only refers to the file name, and I'm not sure how -exclude by path name is still copying the files.

Any help?

+5
source share
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 the path.

+6
source

If we run a little where-objectthrough the pipeline, I think you will get what you are looking for. Every object that has a property named Directory( System.IO.FileInfo) with a property Namewith a value oldwill not be passed to Copy-Item.

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

(unverified)

+4
source

All Articles