Search code examples
powershellcopydirectory-structure

Copy-Item is copying unexpected folder


I'm struggling to understand how PowerShell handles recursion and Copy-Item command.

$date=Get-Date -Format yyyyMMdd
$oldfolder="c:\certs\old\$date"
New-PSDrive -Name "B" -PSProvider FileSystem -Root "\\(server)\adconfig"
$lastwrite = (get-item b:\lcerts\domain\wc\cert.pfx).LastWriteTime
$timespan = new-timespan -days 1 -hours 1

Write-Host "testing variables..."
Write-Host " date = $date" `n "folder path to create = $oldfolder" `n 
"timespan = $timespan"

if (((get-date) - $lastwrite) -gt $timespan) {
#older
Write-Host "nothing to update."
}
else {
#newer
Write-Host "newer certs available, moving certs to $oldfolder"
copy-item -path "c:\certs\wc" -recurse -destination $oldfolder 
copy-item b:\lcerts\domain\wc\ c:\certs\ -recurse -force
}

Existing files exist at c:\certs\wc\cert.pfx I have the "test" comparing the time between the cert.pfx in the b:\lcerts\domain\wc\ folder and the current time . If the cert has been modified in the past 1 day and 1 hour, then the script should continue:

Copy cert.pfx from c:\certs\wc\ to c:\certs\old\$date\cert.pfx

Copy cert.pfx from b:\lcerts\domain\wc to c:\certs\wc\cert.pfx

I obviously don't understand PowerShell nomenclature for this because the first time I run this script, it works fine. The second time it creates another folder inside c:\certs\wc\$date\wc\cert.pfx.

How do I get it to fail with "c:\certs\wc\$date\cert.pfx already exists?"

I don't want to restrict this to just the cert.pfx file by specifying the actual file name, I want all files in the folder as eventually there will be more than one file.


Solution

  • The behavior of Copy-Item when a directory is specified in the -Path parameter depends on whether the directory specified in the -Destination parameter exists.

    Copy-Item -Path "c:\certs\wc" -Recurse -Destination "c:\certs\old\$date"
    

    If the c:\certs\old\$date directory does not exist, then the wc directory is copied and named c:\certs\old\$date.

    If the c:\certs\old\$date directory exists, the wc directory is copied under the c:\certs\old\$date directory. Therefore, it becomes c:\certs\old\$date\wc.

    So you are sure to check in advance if the directory exists.

    if(Test-Path $oldfolder) { throw "'$oldfolder' is already exists." }
    Copy-Item -Path "c:\certs\wc" -Destination $oldfolder -Recurse