0

I need to copy a folder which contains subfolders with files to a shared folder on another machine. During that, the script should create a custom subfolder in each destination folder and place files there.

I hope this example clarifies the task:

  1. For the following source folder:

    --Logs
    ----Application
    ------Service
    --------Log1.txt
    --------Log2.txt
    ------WebSite
    --------Log1.txt
    --------Log2.txt
    
  2. Destination folder should be created in the following way:

    --Logs
    ----Application
    ------Service
    --------Machine1
    ----------Log1.txt
    ----------Log2.txt
    ------WebSite
    --------Machine1
    ----------Log1.txt
    ----------Log2.txt
    

As you see at the bottom level subfolders Machine1 have been created. Can you please provide an example of PowerShell script that can do this?

I investigated input parameters in ROBOCOPY command. It seems it doesn't allow me to do this straightforwardly.

Also I know that I can simply iterate through all folder structure, create required sub folders and copy files to each subfolder, but it seems to be a too 'long' way. So, I want to know if I'm missing anything. Maybe there is a better/smarter way to do this.

  • Did you attempt anything yourself? Or do you want us to just do your work for you? – Dave Feb 6 '14 at 14:14
  • Of course the work for me would be the best my present today (I'm joking). I've added my effort to the question. – Egor4eg Feb 6 '14 at 14:28
  • Right... I think I follow now. You have a solution but want to know if it could improved? That's fair enough, but it will easier to see your code and then see what could be done. You have a 1.6k rep with SO, you should know the drill about sharing code :) – Dave Feb 6 '14 at 14:29
  • I don't have any code yet. I want to make sure that there is a better way to achieve my goal without iterating folder structure before writing any code. Also, I don't expect writing code from your side, I just need an idea how to do that in the best way. – Egor4eg Feb 6 '14 at 14:33
0

Did this quick and dirty code... still iterates though the folder though...

$orgLoc = "test"
$desLoc = "dest"

Copy-Item -Path $orgLoc -Destination $desLoc -Recurse
$stuff = Get-ChildItem -Path $desLoc -Recurse
foreach($thing in $stuff){
    if($thing.Extension -eq ".txt"){
        $newDir = $thing.DirectoryName + "\Machine1"
        if(!(Test-Path $newDir)){
            New-Item -Path $newDir -ItemType Directory
        }
        Move-Item -Path $thing.FullName -Destination $newDir
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.