Powershell Script to Copy Sql Backup files from one server to another server/ remote server

Powershell Script to Copy the Latest Backup File:

This script copy your local sql backup to remote folder and delete old backup files (.bak files). We will provide the folder source, destination folder and then we test destination folder, if folder present all bak files copy to destination folder and delete old backup’s.

An overview of the process looks like below:

  • Search the backup path for files matching a pattern.
  • Find the most recent one, based on date.
  • Copy that most recent file to another location.

Below is the script to copy Latest .bak file from source to destination:

$backuppath = “\\Node1.yourdomainname.com\source” # source path
$destpath = “E:\dest” # Destination path

Get-ChildItem $destpath -recurse -include *.bak -force | remove-item # Remove existing .bak files in destination path

Get-ChildItem -path $backuppath -Filter “*.bak” |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 1 | # last 1 means latest backup file
copy-item -Destination (join-path $destpath $_.name)

If you want to copy 10 or 20 latest or recent .bak files from source folder to destination folder then use below script :

$backuppath = “\\Node1.yourdomainname.com\source” # source path
$destpath = “E:\dest” # Destination path

Get-ChildItem $destpath -recurse -include *.bak -force | remove-item # Remove existing .bak files in destination path

Get-ChildItem -path $backuppath -Filter “*.bak” |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 20 | # last 1 means latest backup file
copy-item -Destination (join-path $destpath $_.name)

Hope this script helps you to copy the backup files .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.