Should Copy-Item create the destination directory structure?

后端 未结 6 1572
广开言路
广开言路 2020-12-08 12:46

I\'m trying to copy a file to a new location, maintaining directory structure.

$source = \"c:\\some\\path\\to\\a\\file.txt\"
destination = \"c:\\a\\more\\dif         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 13:27

    I have been digging around and found a lot of solutions to this issue, all being some alteration not just a straight copy-item command. Grant it some of these questions predate PS 3.0 so the answers are not wrong but using powershell 3.0 I was finally able to accomplish this using the -Container switch for copy-item.

    Copy-Item $from $to -Recurse -Container
    

    this was the test i ran, no errors and destination folder represented the same folder structure.

    New-Item -ItemType dir -Name test_copy
    New-Item -ItemType dir -Name test_copy\folder1
    New-Item -ItemType file -Name test_copy\folder1\test.txt
    #NOTE: with no \ at the end of the destination the file is created in the root of the destination, does not create the folder1 container
    #Copy-Item D:\tmp\test_copy\* D:\tmp\test_copy2 -Recurse -Container
    
    #if the destination does not exists this created the matching folder structure and file with no errors
    Copy-Item D:\tmp\test_copy\* D:\tmp\test_copy2\ -Recurse -Container
    

提交回复
热议问题