Skip to content

Instantly share code, notes, and snippets.

@bijai
Created February 16, 2021 17:10
Show Gist options
  • Save bijai/5415dec7e9357541398ddf6e74d3d5d1 to your computer and use it in GitHub Desktop.
Save bijai/5415dec7e9357541398ddf6e74d3d5d1 to your computer and use it in GitHub Desktop.
Postgres periodic local backup
##Parameters
#Number of backups to keep - oldest backup will be deleted
$threshold = 5
#Where to backup [must be exclusive dir]
$dbDumpPath = 'C:\path\for\dump'
#pgdump binary path
$pgdumpPath = 'C:\path\to\pgdump\binary\PostgreSQL\10\bin\pg_dump.exe'
#database params
$dbName = 'db_name'
$serverHostName = 'localhost'
$serverPort = 5432
$dbUser = "postgres"
$timestamp = Get-Date -Format 'FileDateTime'
$count = (Get-ChildItem -Path "$($dbDumpPath)\*.backup" -File | Measure-Object).Count
Write-Host "Backup count $($count)"
if ($count -ge $threshold)
{
$oldestBackup = Get-ChildItem -Path "$($dbDumpPath)\*.backup" -File | Select-Object -First 1
$oldestLog = Get-ChildItem -Path "$($dbDumpPath)\*.log" -File | Select-Object -First 1
#$contents
Write-Host "Deleting [$($oldestBackup)]"
Remove-Item $oldestBackup
Write-Host "Deleting [$($oldestLog)]"
Remove-Item $oldestLog
}
else
{
Write-Host "Backup count [$($count)] under threshold [$($threshold)]"
}
Write-Host "Starting backup [$(dbName)_$($timestamp)]"
& $pgdumpPath --host $serverHostName --port $serverPort --username $dbUser --format custom --verbose --file "$($dbDumpPath)\$($dbName)_$($timestamp).backup" $dbName 2>&1 | Out-File "$($dbDumpPath)\$($dbName)_$($timestamp).log"
Write-Host "Completed backup [$($dbName)_$($timestamp)]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment