20
votes

I am trying to copy content of a folder, but there are two files which I would like to exclude. The rest of all the content should be copied to a new location and existing content on that new location should be overwritten.

This is my script. It works fine if my destination folder is empty, but if I have files and folder, it doesn't overwrite them.

$copyAdmin = $unzipAdmin + "/Content/*"
$exclude = @('Web.config','Deploy')
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Exclude $exclude -Recurse -force
3
Why not use Robocopy instead?vonPryz
This should work..is there an error message? If this is part of deployment script, maybe the files become locked after copying(which is what would happen if IIS/Website was started).Raf
@raf there is no error . if i do copy paste manually than everything works fine, old files and folders gets over written manually. but with powershell script it only works with target folder is empty than it will not copy web.config file and deploy folder. but say for example if i already have content in destination folder than copy command only copies those files which are missing in destinationsrk786
Is $AdminPath defined correctly in your script?Raf

3 Answers

23
votes

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force
6
votes

Robocopy is designed for reliable copying with many copy options, file selection restart, etc.

/xf to excludes files and /e for subdirectories:

robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"
2
votes

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.