PowerTip: Use PowerShell to Copy Items and Retain Folder Structure

Summary: Copy items in a folder and retain the container with Windows PowerShell 3.0.

Hey, Scripting Guy! Question How can I use Windows PowerShell 3.0 to copy a folder structure from a drive to a network share, and retain the original structure?

Hey, Scripting Guy! Answer Use the Copy-Item cmdlet and specify the –Container switched parameter:

Copy-Item c:\fso –destination \\server1\share -recurse -container

Comments (7)

  1. Best is to do it not with PowerShell!

    There are more than one pitfalls! E.g. See Path too long exception  social.technet.microsoft.com/…/12179.net-powershell-path-too-long-exception-and-a-net-powershell-robocopy-clone.aspx

    You have to maintain the logging and the checksum stuff (Bit checking) by yourself!

    Best practice is to use approved tools like robocopy..exe for such tasks!

  2. Dalmiro says:

    Cool. Had no idea this switch existed

  3. Eric O says:

    Why the need for -container?  Isn't that what -recurse was supposed to do?

  4. June Blender says:

    Container is true by default, so using it doesn’t make any difference.

  5. JS says:

    Thank you for this. Can we take this a step further? I have to admit I finally got the PS bandwagon recently and I am still learning different things you can do with it.
    Anyways, what I am trying to do is basically first pull all the files that 1) are bigger than a certain size and 2) last written to before a certain date, then take those results and copy them to another location while maintaining the directory structure. I
    figured this would be simple but I get an error about the files do not exist locally. Here’s what I did:

    $source=get-childitem -path z:fileserver -r | where-object {$_.length -gt "150MB"} | where-object {$_.lastwritetime -le "1/1/2010"}
    copy-item $source -destination \newserverlocation -r -container

    Shouldn’t this work?


  6. Nithin says:

    Thank you. I got what i want.