Search code examples
powershellbackup

Powershell - Error message for trying to add a date to the end of a copy of a folder


I am new to Powershell and trying to see if I can copy a folder from a Test folder then put it on a Backup folder and rename the folder to the date it was done.

 $sourceFile = "C:\Test1\"
 $destination = "C:\Backup"
 
 
 copy-item $sourceFile -destination $destination .\server-backup-$(Get-Date -format "yyyy_MM_dd_hh_mm_ss") -Recurse

However, I keep getting an error saying cannot be found that accepts arguments.

Copy-Item : A positional parameter cannot be found that accepts argument '.\server-backup-2022_01_20_09_32_27'.
At line:5 char:2
+  copy-item $sourceFile -destination $destination .\server-backup-$(Ge ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Copy-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

Is there a better way of going about this or can this error be easily fixed?


Solution

  • You need to concatenate the destination string:

    $sourceFile = "C:\Test1\"
    $destination = "C:\Backup"
    
    copy-item $sourceFile -destination ($destination + "\server-backup-" + (Get-Date).ToString("yyyy_MM_dd_hh_mm_ss")) -Recurse
    

    I have slightly adjusted your get-date as I am not sure on the output of -format on get-date.

    If you have any spaces in the path then this is considered as a different parameter.

    To avoid this you can use quotes to encapsulate the string, however you cannot execute functions, parenthesis like I have used and concatenating the string is another approach.