Search code examples
powershellcopy-item

Copy-Item Issue using a variable as destination folder name


I am stuck with something weird you may help me.

I am doing the following:

  $DateStringInput=Read-host

Copy-Item -Path "C:\Hodzic\PowerShell\Testordner\Q_Schulungspräsentationen\Vorlage" -Destination "C:\Hodzic\PowerShell\Testordner\Q_Schulungspräsentationen\$DateStringInput_KSF_Grundlagen"  -Recurse

This doesnt work as the error says you cannot overwirte [Folder] with itself...the error repeats for each file contained in the copy-item path.

If I now put a space or anything else in front of "_" in the last part of the destination part it works:

...$DateStringInput _KSF_Grundlagen" or $DateStringInput+_KSF_Grundlagen"

Can you help?


Solution

  • The PowerShell parser interprets all of $DateStringInput_KSF_Grundlagen as a single variable expression.

    Enclose the variable name in {} to prevent that:

    $Destination = "C:\Hodzic\PowerShell\Testordner\Q_Schulungspräsentationen\${DateStringInput}_KSF_Grundlagen"
    Copy-Item -Path "C:\Hodzic\PowerShell\Testordner\Q_Schulungspräsentationen\Vorlage" -Destination $Destination