Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy-Item is overwriting by default

Tags:

powershell

The behaviour I would expect from the code below is:

  1. Grab a list of the files in the source directory.

  2. 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?

like image 842
Supernatix Avatar asked Mar 21 '17 15:03

Supernatix


People also ask

Does copy-item overwrite by default?

By default when you run the PowerShell Copy-Item cmdlet, it will overwrite the file if it is already exists.

How do I copy files without overwriting?

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.

Does PowerShell copy-item overwrite?

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.


1 Answers

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.

like image 176
Ansgar Wiechers Avatar answered Sep 22 '22 13:09

Ansgar Wiechers