Muhammad
Muhammad

Reputation: 93

find latest file name and copy as renamed file in the same folder

I see some kind of similar posts but unfortunately this is not working for me so far. I would like to get the latest backup file (randomly generated) and then copy and rename the file in the same folder with fixed name so that I can schedule the restore job.

Backup files are like:

Fin123.bak
Fin125.bak
Sales456.bak
HRF100.bak

I would like to get the latest file (by creation date) and then copy and rename the file like Fin.bak. In the above files, Fin125.bak is latest backup file which I would like to copy and rename as Fin.bak. The powershell script should ignore all other files like Sales, HR, etc. Only files starting with Fin and having the latest creation date.

Any help is greatly appreciated. Thanks Muhammad

Upvotes: 3

Views: 22021

Answers (4)

Akhilesh Tiwari
Akhilesh Tiwari

Reputation: 1

this works well- but you need to change to Last--becoz- list is descending Select-Object -Last 1

Upvotes: -1

Tabletoni
Tabletoni

Reputation: 11

Wesley's script works OK but have a little error, it use $dir but must be $OriginalDir

$LatestFile = Get-ChildItem -Path $OriginalDir -Name *.bak | Sort-Object LastAccessTime -Descending | Select-Object -First 1

Upvotes: 1

andyb
andyb

Reputation: 2772

This should do the trick.

$bak_path = "path_to_backup_folder"
get-childitem -path $bak_path -Filter "Fin?*.bak" | 
    where-object { -not $_.PSIsContainer } | 
    sort-object -Property $_.CreationTime | 
    select-object -last 1 | 
    copy-item -Destination (join-path $bak_path "FIN.BAK")

Going through it;

$bak_path = "path_to_backup_folder" declare the path to the backup directory as a constant.

get-childitem -path $bak_path -Filter "Fin?*.bak" return a set of objects in folder $bak_path that match the filter "Fin?.bak". The '?' is used to ensure only files with at least one character between 'fin' and '.bak' match.

where-object { -not $_.PSIsContainer } removes any directory objects (just in case).

sort-object -Property $_.CreationTime sorts the list so that the newest file is last in the collection.

select-object -last 1 picks off the last item (ie newest file) and finally

copy-item -Destination (join-path $bak_path "FIN.BAK") copies the last item as FIN.BAK to the same directory

Upvotes: 12

Wesley
Wesley

Reputation: 121

This will work for grabbing the most recent file of the .bak extension.

$OriginalDir = "E:\"
$BackupDir = "H:"
#After the -Name can be changed for whatever you need to backup.
$LatestFile = Get-ChildItem -Path $dir -Name *.bak | Sort-Object LastAccessTime -Descending | Select-Object -First 1
Copy-Item -path "$OriginalDir\$LatestFile" "$BackupDir\$LatestFile"

Upvotes: 3

Related Questions