Sql-server – T-SQL or PowerShell to move bak files older than 2 days to another location

disk-spacepowershellsql serversql-server-2005t-sql

I'm using SQL Server 2005. One of my backup drives is filling up, so I want to move backups older than 2 days.

I was thinking of creating a job to run everyday, but got stuck on the scripts moving the .bak files.

Do you know a script to move files from drive A and move it to a shared location? My .bak files doesn't have a timestamp.

Best Answer

This Powershell example will find all .bak files older than two days in the c:\backup folder and move them to \shared\archive shared drive.

Get-ChildItem c:\backup\*.bak |where {$_.LastWritetime -lt (get-date).adddays(-2)} |move-item -Destination \\shared\archive

Note you cannot run PowerShell commands directly in SSMS. Try it in a SQL Server Agent job step, or just in a PowerShell command window. Should work fine in either.