tags:

views:

1656

answers:

1

I have the following snippet of Powershell script:

$source = 'd:\t1\*'
$dest = 'd:\t2'
$exclude = @('*.pdb','*.config')
Copy-Item $source $dest -Recurse -Force -Exclude $exclude

Which works to copy all files and folders from t1 to t2 but it only excludes the exclude list in the "root"/"first-level" folder and not in sub-folders.

Anybody know how to make it exclude the the exclude list in all folders?

+10  A: 

I think the best way is to use Get-ChildItem and pipe in the Copy-Item command.

I found that this worked:

$source = 'd:\t1'
$dest = 'd:\t2'
$exclude = @('*.pdb','*.config')
Get-ChildItem $source -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($source.length)}

Basically, what is happening here is that you're going through the valid files one by one, then copying them to the new path. The 'Join-Path' statement at the end is so that the directories are also kept when copying over the files. That part takes the destination directory and joins it with the directory after the source path.

I got the idea from here, and then modified it a bit to make it work for this example.

I hope it works!

landyman
That was just the solution I was going to post. :) I have found that -Include and -Exclude do not work right for Select-String, Copy-Item, and some other commands. It does work right for Get-ChildItem (dir).
JasonMArcher
IIRC, if you look at the help file for those cmdlets, they state those parameters do not work as expected. To ship is to choose.
James Pogran
Thanks Aaron - that worked perfectly!
Guy