From d00aa717dbec75dad59b9110ee0b87baa6785a8a Mon Sep 17 00:00:00 2001 From: "b.nehlsen" Date: Wed, 29 Jul 2026 21:09:29 +0200 Subject: [PATCH] initial commit --- Backup_DB_Keyvi.ps1 | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Backup_DB_Keyvi.ps1 diff --git a/Backup_DB_Keyvi.ps1 b/Backup_DB_Keyvi.ps1 new file mode 100644 index 0000000..b00831f --- /dev/null +++ b/Backup_DB_Keyvi.ps1 @@ -0,0 +1,38 @@ +$Server = ".\KEYVI" +$Database = "DB_Keyvi" +$BackupRoot = "D:\SQLBackup\DB_Keyvi" +$RetentionDays = 365 + +$now = Get-Date +$year = $now.ToString("yyyy") +$month = $now.ToString("MM") + +# Zielordner: D:\SQLBackup\DB_Keyvi\YYYY\MM\ +$BackupDir = Join-Path (Join-Path $BackupRoot $year) $month +New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null + +# Dateiname: DB_Keyvi_yyyyMMdd_HHmmss.bak +$timestamp = $now.ToString("yyyyMMdd_HHmmss") +$BackupFile = Join-Path $BackupDir ("{0}_{1}.bak" -f $Database, $timestamp) + +# Backup +$sql = "BACKUP DATABASE [$Database] TO DISK = N'$BackupFile' WITH CHECKSUM, STATS = 10;" +sqlcmd -S $Server -E -C -Q $sql +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + +# Alte Backups löschen +$cutoff = (Get-Date).AddDays(-$RetentionDays) +Get-ChildItem -Path $BackupRoot -Recurse -File -Filter "*.bak" | + Where-Object { $_.LastWriteTime -lt $cutoff } | + Remove-Item -Force + +# Leere Ordner löschen (von unten nach oben) +Get-ChildItem -Path $BackupRoot -Recurse -Directory | + Sort-Object FullName -Descending | + ForEach-Object { + if (-not (Get-ChildItem -Path $_.FullName -Force | Select-Object -First 1)) { + Remove-Item -Path $_.FullName -Force + } + } + +exit 0 \ No newline at end of file