Search code examples
powershellcopy-item

PowerShell Copy-Item what I'm doing wrong?


Given the dir structure:

x\Code
x\Script\Backup.ps1

Backup.ps1 contains:

$BackupDirectoy       = "..\Backup"
$CodeDirectory        = "..\Code"

function BackupCurrentVersion()
{
  New-Item $BackupDirectoy -type directory -force
  Copy-Item $CodeDirectory -destination $BackupDirectory -recurse
}

BackupCurrentVersion

I'm doing something wrong because Code gets copied in x\Script\Code instead of x\Backup\Code

What is the problem?


Solution

  • $BackupDirectoy       = "..\Backup"
    $CodeDirectory        = "..\Code"
    

    These paths are going to be relative to the current dir your prompt is sitting in when you run the script. I suspect you don't want that but want to run relative to where the script is located. Try this if this is the case:

    $ScriptDir      = Split-Path $MyInvocation.MyCommand.Path -Parent
    $BackupDirectoy = "$ScriptDir\..\Backup"
    $CodeDirectory  = "$ScriptDir\..\Code"