tympaniplayer
tympaniplayer

Reputation: 171

Powershell exclude recursively

I seem to be having trouble with exclusions and copying directories recursively in powershell.

I want to copy a directory recursively, but have it include any file that matches test.txt.

My Source directory looks like this

Running the command below results with the following output. Where it copies excludes the first instance of test.txt, but not the second. What am I missing?

My Script:

Get-ChildItem -Path .\TestDir -Recurse -Exclude test.txt | Copy-Item -Destination .\temporary -Recurse -Exclude text.txt

Upvotes: 0

Views: 428

Answers (1)

Michael B
Michael B

Reputation: 12228

I confess, I Nerd Sniped myself into doing this, with a 'well that can't be hard...'

The problem appears to be that if copy-item gets the slightest whiff of a directory it just copies the whole thing without any consideration of what's inside it, completely ignoring any concept of filtering along the way!

While trying to solve the filtering problem I stumbled upon this excellent answer -

Your solution appears to be something like this -

$source = "E:\PS\test-output\test"
$dest = "E:\PS\test-output\test1"
$exclude = @('test.txt') 
Get-ChildItem $source -Recurse -Exclude $exclude `
    | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($source.length)}

This ditches copy-item's (seemingly braindead) recursion and builds your own.

Upvotes: 2

Related Questions