ADTJOB
ADTJOB

Reputation: 85

Copy most recent file from folder to destination

I need some assistance with powershell . My experience is very limited as I'm a sql server dba. What I am currently doing is migrating databases across from 2000 to 2008. I want to automate the .bak copy from source to destination so I don't need to go into each folder and copy and then paste. So let me give the picture. The source directory has folders a b c d. I want the script to read from each folder or ideally specify the folder names and get the most recent .Bak full backup by date and copy to a destination. The destination will have the same folders so folder a's backup copied to destination folder a will be great. Afterwards I want to do the same but change my search from full backup search to differential. Any help is appreciated.

Upvotes: 0

Views: 6819

Answers (2)

Sean Rhone
Sean Rhone

Reputation: 268

This is how I would address it. The variables for folderpath and destination path are the root folders and the variable for childfolders list out each folder to search.

Clear-Host
$ChildFolders = @('A', 'B')

for($i = 0; $i -lt $ChildFolders.Count; $i++){

    $FolderPath = "D:\BackupSource\" + $ChildFolders[$i]
    $DestinationPath = "D:\BackupDestination\" + $ChildFolders[$i]

    gci -Path $FolderPath -File | Sort-Object -Property LastWriteTime -Descending | Select FullName -First 1 | %($_){ 
    $_.FullName
    Copy-Item $_.FullName -Destination $DestinationPath 
    }

}

Upvotes: 1

Justus
Justus

Reputation: 56

Given this structure, meaning all folders exist.

├───destination
│   ├───A
│   └───B
└───source
    ├───A
    └───B

You can do the following:

$folders = @('A', 'B')
$source = 'source'
$destination = 'destination'
$filter = '*.bak'

$folders | foreach {
    $source_path = [io.path]::combine($source, $_)
    $destination_path = [io.path]::combine($destination, $_)
    gci $source_path -File -Filter $filter | sort -Property LastWriteTime -Descending | 
        Select -first 1 | copy -Destination $destination_path
}

It gets all files matching your filter, sorts them in descending order by LastWriteTime, picks the newest and copies it to your destination.

Upvotes: 0

Related Questions