The behaviour I would expect from the code below is:
Grab a list of the files in the source directory.
Loop through and copy each file to the backup destination, only if it does not already exist.
if (!(Test-Path C:\Folder\Destination)) {
New-Item -ItemType Directory -Force -Path C:\Folder\Destination
}
$originalfiles = Get-ChildItem -Path "C:\Folder\Source"
$originalfiles
foreach ($file in $originalfiles) {
Write-Host
Write-Host File Name: -ForegroundColor DarkYellow
Write-Host $file.Name
Write-Host File Path: -ForegroundColor DarkYellow
Write-Host $file.FullName
$src = $file.FullName
$dest = "C:\Folder\Destination\$($file.Name)"
Copy-Item $src $dest
}
I would have thought that the Copy-Item
cmdlet defaults to NOT overwrite, unless you specify the -Force
flag. This is the behaviour I have seen in the past when I originally encountered situations where I did want to overwrite.
Also, I thought it may be the introduction of the foreach
loop but I tried the copy command, on it's own, with hardcoded paths for a single file, and it is still the same.
Should I restart my IDE, or is it a mistake I have overlooked?
By default when you run the PowerShell Copy-Item cmdlet, it will overwrite the file if it is already exists.
Switches are explained below. /XC − Prevents overwriting the files which have the same timestamp. /XN − Prevents overwriting of files with the newer timestamp than the source files. /XO − Prevents overwriting of files with the older timestamp than the source files.
The Copy-Item cmdlet has the Container parameter set to $false . This causes the contents of the source folder to be copied but doesn't preserve the folder structure. Notice that files with the same name are overwritten in the destination folder.
When in doubt, read the documentation.
-Force
Indicates that this cmdlet copies items that can't otherwise be changed, such as copying over a read-only file or alias.
The default behavior for Copy-Item
is to replace existing items. The -Force
switch is only to enforce replacement if for instance the destination file has the readonly attribute set.
You can use -Confirm
to get prompted before Copy-Item
performs the operation, or you can use -WhatIf
to see what the cmdlet would do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With