Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite files with Copy-Item in PowerShell

Tags:

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 
like image 559
srk786 Avatar asked Sep 25 '14 11:09

srk786


People also ask

Does PowerShell copy item overwrite existing files?

By default, when you will copy item in PowerShell using the Copy-Item, it will overwrite the files in the destination folder. The above PowerShell script will overwrite the files but it will show an error for folders: Copy-Item : An item with the specified name D:\Bijay\Destination\Folder1 already exists.

How do I overwrite a copy of a file?

Usually, when you run a cp command, it overwrites the destination file(s) or directory as shown. To run cp in interactive mode so that it prompts you before overwriting an existing file or directory, use the -i flag as shown.

How do you overwrite in PowerShell?

To overwrite an existing file, use the –Force switch parameter.

How do you overwrite a text file in PowerShell?

After Get-Content reads the file and passes the string to the replace operator, PowerShell then hands off that new string to Set-Content, which takes that string as pipeline input and overwrites the existing file. Voila!


2 Answers

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 
like image 171
Daniel Lindegaard Avatar answered Sep 22 '22 06:09

Daniel Lindegaard


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" 
like image 29
clD Avatar answered Sep 26 '22 06:09

clD