Copying of last modified files to another folder and following structure.

<p style=“text-align: right;”>Hi, I am a newbie to powershell.My requirement is copying last modified file to destination folder.The files and subfolder name also need to copied.</p>
<p style=“text-align: right;”>Let me explain clearly by structure.</p>
<p style=“text-align: right;”>Source</p>
<p style=“text-align: right;”>Subfolder:1</p>
<p style=“text-align: right;”>Text1.</p>
<p style=“text-align: right;”>Text2(last modified)</p>
<p style=“text-align: right;”>Subfolder 2</p>
<p style=“text-align: right;”>Text3</p>
<p style=“text-align: right;”>Text4(last modified)</p>
<p style=“text-align: right;”>Subfolder</p>
<p style=“text-align: right;”>Text5</p>
<p style=“text-align: right;”>Text6</p>
Output:This is what I need





<p style=“text-align: right;”></p>

Did you consider using robocopy? It has plenty of options to specify the files to copy.

Did you try to find something fitting in the PowershellGallery?

<p style=“text-align: center;”>I am using script like this…But this copies only files but not sub folder name</p>

$Targetfolder= "C:\Users\Vamsy\desktop\Continuous Integration\Target"

$Sourcefolder= "C:\Users\Vamsy\desktop\Continuous Integration\Source"

$files = get-childitem $Sourcefolder -file | 
          where-object { $_.LastWriteTime -gt [datetime]::Now.AddMinutes(-5) }|
          Copy-Item -Path $files -Destination $Targetfolder -recurse -Force

Please take a look at robocopy. I linked the documentation in my first answer. There’s actually no need for a script.

But robocopy operation is used only for date…but not in minutes…


OK, you did not specify the desired age in your first post.

With this requirement you will have to extract the part of the source path you want to mirror in the target, create the target folder first before you’re able to copy the file to the newly created desitnation folder.

There are several examples throughout the internet for Powershell scripts with this kind of requirements. You should search for it in the PowershellGallery or StackOverflow or in the Microsoft Technet Forums. You don’t have to re-invent the wheel.

If you like to do it by yourself anyway … the following example illustrates how to extract the target folder structure:

$StartFolder = 'D:\sample\test'
$FileFullName = 'D:\Sample\Test\SubFolder1\Test2\File.txt'
$SourceFolder = Split-Path $FileFullName -Parent
$TargetFolderStructure = $SourceFolder -replace [regex]::Escape($StartFolder)

BTW: You could leverage the ability of robocopy to filter on the archive attribute with the option /M