Geeks With Blogs
Sean Rhone
Saw a question like this on Stack Overflow and submitted this answer and thought I'd like to keep it around for future use. The task was to find the newest file in a directory and copy it to another folder.


Clear-Host

# List of all child folders under base folder
$ChildFolders = @('A', 'B')

#Iterate over collection of child folders
for($i = 0; $i -lt $ChildFolders.Count; $i++){

    # Build the folder to search for newest folder
    $FolderPath = "D:\BackupSource\" + $ChildFolders[$i]

    # Build destination folder
    $DestinationPath = "D:\BackupDestination\" + $ChildFolders[$i]

    # use Get-ChildItem to search folders. Note the Sort and Select
    gci -Path $FolderPath -File | Sort-Object -Property LastWriteTime -Descending 
             | Select FullName -First 1 
             | %($_){Copy-Item $_.FullName -Destination $DestinationPath 
                         }
    
}

So, this code expects the source and destination folder structure be the same. It does not check if the source file exists in the destination (already copied over earlier).
Posted on Thursday, January 21, 2016 10:33 AM PowerShell | Back to top


Comments on this post: Finding the newest file in folder using PowerShell

# re: Finding the newest file in folder using PowerShell
Requesting Gravatar...
It does work well. I like the idea, it is what I expected. - Steve Wyer
Left by Lindsay Miller on Aug 08, 2016 11:53 PM

Your comment:
 (will show your gravatar)


Copyright © Sean Rhone | Powered by: GeeksWithBlogs.net