0

Trying to create a simple backup script, but every time I run the script below, I receive the following error:

Copy-Item : Cannot overwrite the item C:\Users\Jacob\desktop\file1.txt with 
itself.
At C:\Users\Jacob\desktop\test.ps1:5 char:1
+ Copy-Item $file $file.backup
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\Jacob\desktop\file1.txt:String) [Copy-Item], IOException
    + FullyQualifiedErrorId : CopyError,Microsoft.PowerShell.Commands.CopyItemCommand

Simple script:

Param(
    [Parameter(Mandatory=$true)]
    [string]$file
)

Copy-Item $file $file.backup
"$file has been backed up."
2
  • Great, but do you understand why it worked? Commented Jan 26, 2018 at 18:43
  • Please do not edit an answer into the question. If you found a solution yourself it's perfectly acceptable to post it as an answer of your own. Commented Jan 26, 2018 at 18:51

1 Answer 1

0

$file.backup tries to expand the (non-existing) property backup on the string variable $file. This comes back with an empty result, so you're effectively running Copy-Item $file (without a destination), which causes the error you observed.

To avoid this issue you can do several things, for instance:

  • define the destination as a string:

    Copy-Item $file "${file}.backup"
    
  • append the extension by string concatenation:

    Copy-Item $file ($file + '.backup')
    
  • use the format operator:

    Copy-Item $file ('{0}.backup' -f $file)
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.