Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copy most recent files from a list of directories

Status
Not open for further replies.

RRinTetons

IS-IT--Management
Jul 4, 2001
333
US
I want to give PowerShell an explicit list of file paths to several directories and have it copy the most recent file found in each directory to a common location.

e.g., given the list

Z:\RTPSQL\DataFileBackups\RTPOne
Z:\Dynamics-GP
Z:\TimeCentre\tc2kdb
Z:\FoodTrak
Z:\FleetMax

I want to get the most recent file out of each of those directories and copy it to another directory named

C:\ForArchive

I have scripts to copy the entire contents of a directory, or to copy an explicit file name from a directory, but not to get the most recent file regardless of its name.

Suggestions?


-
Richard Ray
Jackson Hole Mountain Resort
 
i don't know the syntax, but the logic would look like this:
for each directory
1. get a list of all files in the directory
2. order files by create date in descending order
3. take the first file
4. copy the file

in c# this is simple enough
Code:
new [] {
@"Z:\RTPSQL\DataFileBackups\RTPOne",
@"Z:\Dynamics-GP",
@"Z:\TimeCentre\tc2kdb",
@"Z:\FoodTrak",
@"Z:\FleetMax"
}
.Select(directory => new DirectoryInfo(directory))
.Where(directory => directory.Exists)
.Select(directory => directory
                      .GetFiles()
                      .OrderByDescending(file => file.CreationTime)
                      .FirstOrDefault())
.Where(file => file != null)
.ToList()
.ForEach(file => File.CopyTo(@"C:\ForArchive\")
with PS i'm sure you could somehow pipe for a clean script. something like
Code:
@(
"Z:\RTPSQL\DataFileBackups\RTPOne",
"Z:\Dynamics-GP",
"Z:\TimeCentre\tc2kdb",
"Z:\FoodTrak",
"Z:\FleetMax"
)
select-object {get-childitem $_ | sort-object $_.CreationTime -desc | select-object -first 1} | where $_ != null | copy-object $_ "c:\ForArchive\"

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top