Powershell Basics: Prompt To Copy File If It Does Not Exist


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:

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

PowerShell_Tips_Tricks_thumb.png

Comments (1)

Skip to main content