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).