0

I have the source folder structure as shown below

c:\TestResults
|-- Log
|   |-- xyz.pdf
|   `-- Reports
|       `-- rp.pdf
|-- Keywords
|   |-- key.txt
|   |   `-- pb.ea
|   `-- reports
|-- Test
|   |-- 11.pdf
|   |-- 12
|   `-- Log
|       |-- h1.pdf
|       `-- Reports
|           `-- h2.pdf
`-- Dev
    |-- st
    |-- ea
    `-- Log
        `-- Reports
            `-- h4.pdf

I need to copy all the "Log" folders while maintaining the folder structure. The destination path is "c:\Work\Logs\TestResults". The resultant structure should be as shown below.

c:\Work\Logs\TestResults
|-- Log
|   |-- xyz.pdf
|   `-- Reports
|       `-- rp.pdf
|-- Test
|   `-- Log
|       |-- h1.pdf
|       `-- Reports
|           `-- h2.pdf
`-- Dev
    `-- Log
        `-- Reports
            `-- h4.pdf

Is there an easy way of achieving this using a powershell script? Thanks!

Edit: Here's the code that I have written so far. It flattens the folder structure but doesn't maintain the hierarchy. I am new to powershell scripting. Please help.

$baseDir = "c:\TestResults"
$outputDir = "c:\Work\Logs"
$outputLogsDir = $outputDir + "\TestResults"
$nameToFind = "Log"

$paths = Get-ChildItem $baseDir -Recurse | Where-Object { $_.PSIsContainer -and $_.Name.EndsWith($nameToFind)}

if(!(test-path $outputLogsDir))
{
   New-Item -ItemType Directory -Force -Path $outputLogsDir
}


foreach($path in $paths)
{
   $sourcePath = $path.FullName + "\*"   
   Get-ChildItem -Path $sourcePath | Copy-Item -Destination $outputLogsDir -Recurse -Container
}                 
2
  • As is this is a "give me teh codez" question. I suggest you take a look here and try some code first adamtheautomator.com/copy-item-copying-files-powershell Commented Jan 14, 2019 at 1:50
  • I will edit the question to include the code that I have written. The problem that I am having is that the folder structure is getting flattened out and doesn't maintain the hierarchy. Commented Jan 14, 2019 at 1:55

1 Answer 1

1

What you are after is as below. it will copy the item and dir if any part of it has "\log" in it.

$gci = Get-ChildItem -Path "C:\TestResults" -Recurse

Foreach($item in $gci){
    If($item.FullName -like "*\log*"){
        Copy-Item -Path $item.FullName -Destination $($item.FullName.Replace("C:\TestResults","C:\Work\Logs\TestResults")) -Force
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.