Copy files from directory structure but exclude a named folder
Asked Answered
T

2

5

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?

Therewithal answered 7/2, 2012 at 23:34 Comment(0)
B
6

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.

Biological answered 7/2, 2012 at 23:52 Comment(3)
The question was a little ambiguous, and I couldn't tell if an "old" folder would have subfolders or not. This excludes both.Biological
Yes, it was ambiguous, and I did want the subfolders of 'old' excluded. I should have specified that. Thanks again!Therewithal
For anyone else trying to use this, the "*.txt needs a closing quotation "*.txt" for this to work, but the typo was in the original question so it ended up in all the answers I suppose.Garlic
E
4

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)

Escheat answered 7/2, 2012 at 23:51 Comment(1)
Thanks, this is what I asked for. I appreciate the explanation on how to access the directory name. This will prove useful. Thank you!Therewithal

© 2022 - 2024 — McMap. All rights reserved.