Skip to content

Instantly share code, notes, and snippets.

@alwalker
Created January 26, 2016 14:42
Show Gist options
  • Save alwalker/2509aab9ec54864ba3fe to your computer and use it in GitHub Desktop.
Save alwalker/2509aab9ec54864ba3fe to your computer and use it in GitHub Desktop.
Script for taking a full backup of a sql express database then cleaning up the previous weeks backups
$limit = (Get-Date).AddDays(-8)
sqlcmd -S pmssql -E -Q "EXEC sp_BackupDatabases @backupLocation='D:\backups\', @backupType='F', @databaseName='dashboard'"
if ($LASTEXITCODE -eq 0) {
$path = "D:\backups"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment