unexpected structure when copying folders in Windows Powershell

前端 未结 1 1094
死守一世寂寞
死守一世寂寞 2021-01-22 12:17

I have a set of projects that involve a mix of project-specific files plus common files. I\'m trying to copy contents from two different folders -- a project-specific folder, an

相关标签:
1条回答
  • 2021-01-22 12:45

    The behavior you describe is a known problem as of Windows PowerShell v5.1 / PowerShell Core v6.2.0-preview.2, unfortunately:

    In short, the behavior of Copy-Item regrettably depends on whether the target directory happens to exist already or not:

    If the target dir. exists, it is not the source directory's content that is copied, but the source dir. as a whole, to a subdirectory of the target directory named for the source dir.


    The workaround is already mostly spelled out in PetSerAl's helpful comment on the question:

    • Before copying, make sure that the target directory exists.

    • Append \* to the source path to explicitly target the contents of the source dir.

      • Also specify -Force, so as to ensure that hidden files and directories are also copied.
    $pkgContentPath = "bld\$project\pkg_contents"
    
    # Make sure the target dir. exists.
    # (-Force leaves an existing dir alone and otherwise creates it.)
    New-Item -Force -Type Directory $pkgContentPath
    
    # IF desired, clear out the pre-existing directory content.
    # !! Beware of Remove-Item's intermittent failures - see below.
    #  Remove-Item -Force $pkgContentPath\* -Recurse.
    
    # Copy with \* appended to the source paths and -Force added:
    #
    # copy common files
    Copy-Item -Recurse -Force -Path .\src\Common\PackageAssets\* $pkgContentPath
    # copy project-specific files
    Copy-Item -Recurse -Force -Path .\src\Projects\ProjectA\PackageFiles\* $pkgContentPath
    

    A note re use of Remove-Item -Recurse to clear out preexisting destination-directory content, if needed: Regrettably, Remove-Item can fail on occasion and you cannot predict when that happens - see this answer for a robust alternative.

    0 讨论(0)
提交回复
热议问题