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 Wednesday, January 20, 2016 2:38 PM 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...
Thanks for the idea. This would be a useful idea as I begin my new project soon. - Bath Planet
Left by Greg Williams on Sep 18, 2016 10:47 PM

Your comment:
 (will show your gravatar)


Copyright © Sean Rhone | Powered by: GeeksWithBlogs.net