Norrin Rad
Norrin Rad

Reputation: 991

Powershell Copy Last Modified File

I'm trying to copy some files from a source to a destination, however the source has multiple folders and in the folders I'd like to copy just the last file.

I can isolate the last file with the folowing:

gci 'D:\Data' | sort LastWriteTime | select -last 1 -recurse

It only selects the last file in the folder, so I thought a loop would do it, such as:

$file = gci 'D:\Data' foreach ($files in $file) { sort LastWriteTime | select -last 1 | Copy-Item C:\Test\data} 

However this keeps failing

Can someone point me in the right direction.

Upvotes: 1

Views: 5193

Answers (1)

Nas
Nas

Reputation: 1263

Get-ChildItem D:\Data -Directory | ForEach-Object {
    Get-ChildItem $_.FullName -File -Recurse | 
        Sort-Object -Property LastWriteTime | 
            Select-Object -Last 1 | 
                Copy-Item -Destination C:\Test\data
}

Upvotes: 3

Related Questions