Copy certain folder and subdir, but keep folder structure

This topic contains 6 replies, has 4 voices, and was last updated by  Curtis Smith 2 weeks, 1 day ago.

  • Author
    Posts
  • #76539

    Klaus
    Participant

    Hi.

    I have a folder with +2500 projekt folders like this:

    Projekt1
    -folder1
    -folder2
    -folder3

    Projekt2
    -folder1
    -folder2
    -folder3

    Projekt3
    -folder1
    -folder2
    -folder3

    And so on.

    I am looking for a PS script to help me copy certain folders and sub folders, to another network share. I am not that good at PS, so I've found a script, but it does not include empty folders. And I really need all folders, because every projekt folder is auto generated from a template, so a lot of folders is empty to begin with.

    The script looks like this and find the folder named "2_ STXP Tegninger", then copy it to the set target including the folder structure:

    $source = 'C:\Temp\STXP\Projekter'
    $target = 'C:\Temp\STXP\Test'
    $source_regex = [regex]::escape($source)
    (gci $source -recurse | where {-not ($_.psiscontainer)} | select -expand fullname) -match '\\2_ STXP Tegninger\\' |
    foreach {
    
    $file_dest = ($_ | split-path -parent) -replace $source_regex,$target
    
    if (-not (test-path $file_dest)){mkdir $file_dest}
    copy-item $_ -Destination $file_dest
    }
    

    Can somebody please help getting every folder copied, empty or not?

    Thank you.

  • #76654

    js
    Participant

    Not this?

    $source = 'C:\Temp\STXP\Projekter'
    $target = 'C:\Temp\STXP\Test'
    ls -r $source | where { $_ -match '2_ STXP Tegninger' } | cp -r -destination $target -whatif
    
  • #76677

    Klaus
    Participant

    Hi thanks for the reply.

    I just googled for something to help me solve the problem. I have a very very limited knowledge about PS.

    So this is me learning 🙂

    I understand what you are writting, but is does not keep the parent folder and the the script can only copy the first folder it finds, the rest just error out with "allready exist".

    • #76701

      Olaf Soyk
      Participant

      robocopy source destination /E

  • #76755

    Klaus
    Participant

    Hi.

    I tried to go through every step in the script I allready provided, and I found out, that this:

    where {-not ($_.psiscontainer)}

    Mean it does not include the empty folders. I removed that part, and now it works as it should 🙂

    • #76759

      Olaf Soyk
      Participant

      Actually that excludes folders at all – not only empty ones. But again – what you're about to create with your code is actually all build in in robocopy. You don't have to invent the wheel again. It's already there. 😉

  • #76765

    Curtis Smith
    Participant

    I agree with Olaf. This is one of those right tool for the job things. Robocopy will do exactly what you are describing.

You must be logged in to reply to this topic.