Prevent overwrite of files by Copy-Item in PowerShell

The PowerShell command Copy-Item will overwrite a file if it exists by default. This is unless that file is marked Read Only in which case you can use the -Force switch to overwrite the file.

What if you want to only copy the file if it doesn’t exist? Here’s a quick PowerShell script that will complete this task:

$sourceFile = 'c:\temp\something.txt'
$destinationFile = 'c:\temp\1\something.txt'
if (-not (test-path $destinationFile))
  $opts = @{'path' = $sourceFile; 'destination' = $destinationFile; 'confirm' = $false}
  copy-item @opts
   $opts = @{'path' = $sourceFile; 'destination' = $destinationFile; 'confirm' = $true}
   copy-item @opts

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s