Copy-Item is overwriting by default

When in doubt, read the documentation.

-Force

Allows the cmdlet to copy items that cannot 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.


Old one, but I found a short expression that does that:

Copy-Item (Join-Path $dir_from "*") $dir_to -Exclude (Get-ChildItem $dir_to)

It copies all files from $dir_from to $dir_to but not (the -Exclude part) the files with names that are already in $dir_to


It seems to be the expected behaviour of Copy-Item to copy an item to the destination even if it already exists in destination. I suggest to test, if the destination file path exists and only copy the file if it does not yet exist.

$destinationPath = 'C:\tryout\destination';
if (!(Test-Path $destinationPath)) 
{
   New-Item -ItemType Directory -Force -Path $destinationPath;
}

$sourcePath = 'C:\tryout\source';
$originalfiles = Get-ChildItem -Path $sourcePath;
$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:\tryout\destination\$($file.Name)";

    if (!(Test-Path $dest))
    {
        Copy-Item $src -Destination $dest;
    }
}

Tags:

Powershell