Search code examples
powershellpowershell-remoting

Copy-Item -Recurse skips Creation of one sub-directory


I want to copy all files with all subdirectories to another machine (using a WinRM session) and the copy part of my script looks like this:

$sourceDir = "C:\Build\Application1"
$targetDir = "C:\Install\Application1"
Copy-Item -ToSession $session -Path $sourceDir\* -Destination $targetDir -Recurse -Force

$sourceDir contains two subdirectories:

C:\Build\Application1 (3 files)
             |
             +--- Application Files (empty)
                         |
                         +--- Application_2016_12_10_2 (10 files)

Scenario 1

If the folder Application1 does not exist yet in C:\Install, the destination folder structure looks like this after executing my script:

C:\Install\Application1 (3 files)
             |
             +--- Application_2016_12_10_2 (10 files)

Scenario 2

If the folder Application1 already exists in C:\Install, the destination folder structure looks like this as expected:

C:\Install\Application1 (3 files)
             |
             +--- Application Files (empty)
                         |
                         +--- Application_2016_12_10_2 (10 files)

Why is my script not creating the folder Application Files in the first scenario? Can someone clarify?

I'm using Powershell 5


Solution

  • See the issue what you are facing is because you are telling powershell to copy the items from the sourcedir\* . As a result, it is looking for the content of it.

    So just use this directly and it will work :

    $sourceDir = "C:\Build\Application1"
    $targetDir = "C:\Install\Application1"
    Copy-Item -ToSession $session -Path $sourceDir -Destination $targetDir -Recurse -Force
    

    Hope it helps