Script not maintaining directory structure

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of crashrebootrepeat crashrebootrepeat 1 year, 5 months ago.

  • Author
    Posts
  • #33082
    Profile photo of crashrebootrepeat
    crashrebootrepeat
    Participant

    This script is copying files and is maintaining the lastwritetime which is important. However, everything is getting dumped into the root of my destination folder rather than maintaining directory structure. I read on scripting guy that the -containiner would make things go where they came from, but it's not working.

    I have to use the subst t: because my file names are to long otherwise.

    subst t: \\server.domain.com\dir\
    Get-ChildItem -path T: -Recurse | where-object {$_.lastwritetime -gt (Get- Date).Adddays(-124)} | Copy-Item -destination C:\DEST\ -Container -Force

  • #33083
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Copy-Item will only maintain the directory structure if you're copying an entire folder from one place to another. What you're actually doing is copying a bunch of files, piping each one individually into the same destination.

    In practice, I'd probably just use robocopy.exe for this, since it has everything you need anyway. But if you want to use PowerShell with Get-ChildItem and Copy-Item, you'll need to figure out the full target path yourself. I do this in several bits of my own code, using this Get-RelativePath function:

    function Get-RelativePath
    {
        param ( [string] $Path, [string] $RelativeTo )
        return $Path -replace "^$([regex]::Escape($RelativeTo))\\?"
    }
    

    For example:

    function Get-RelativePath
    {
        param ( [string] $Path, [string] $RelativeTo )
        return $Path -replace "^$([regex]::Escape($RelativeTo))\\?"
    }
    
    Get-ChildItem -Path T:\ -Recurse |
    Where-Object {$_.lastwritetime -gt (Get-Date).Adddays(-124)} |
    Copy-Item -Destination { Join-Path C:\DEST (Get-RelativePath -Path $_.FullName -RelativeTo T:\ )  } -Container -Force -WhatIf
    
    
  • #33084
    Profile photo of crashrebootrepeat
    crashrebootrepeat
    Participant

    Thanks Dave that did the trick.

You must be logged in to reply to this topic.