Update AdHoc-Backup.ps1

This commit is contained in:
Mattia Tadini 2025-11-10 12:35:58 +00:00
parent 37baf0381f
commit 8865f4387c

View File

@ -1,5 +1,5 @@
<#
Backup_AdHoc_rclone_mail_fixed_v3_fix26.ps1
Backup_AdHoc.ps1
Fix:
- PowerShell è case-insensitive: le variabili locali "$files" sovrascrivevano "$Files" (hashtable globale).
Rinominati i locali in "$outFiles" e, in Write-Log, uso esplicito di $script:Files.Log per evitare collisioni.
@ -450,7 +450,47 @@ function Get-OnlineUserDatabases {
Log-SqlcmdArgsSafe -Args $sqlArgs
$res = @(& $SqlcmdExe @sqlArgs 2>$null)
if ($LASTEXITCODE -ne 0) { throw "sqlcmd fallito nell'enumerazione DB." }
$names = @()
function Ensure-BackupGrants-ForSystem {
param([string]$SqlcmdExe, [string[]]$DbList)
# Concede BACKUP DATABASE / BACKUP LOG a 'NT AUTHORITY\SYSTEM' su TUTTI i DB utente.
# Nota: è idempotente e viene eseguito prima del backup.
try {
if (-not $SqlcmdExe) { $SqlcmdExe = Resolve-Sqlcmd }
if (-not $DbList -or @($DbList).Count -eq 0) { return }
foreach ($db in @($DbList)) {
$sql = @"
USE [$db];
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = N'NT AUTHORITY\SYSTEM')
CREATE USER [NT AUTHORITY\SYSTEM] FOR LOGIN [NT AUTHORITY\SYSTEM];
GRANT BACKUP DATABASE TO [NT AUTHORITY\SYSTEM];
GRANT BACKUP LOG TO [NT AUTHORITY\SYSTEM];
"@
$tmpSql = Join-Path $Paths.SqlStage ("grant_system_{0}.sql" -f $db)
$sql | Out-File -LiteralPath $tmpSql -Encoding ASCII -Force
$sqlArgs = Build-SqlcmdArgs -WindowsAuth:$SqlUseWindowsAuth -User $SqlUser -Password $SqlPassword -Instance $SqlInstance -InputFile $tmpSql
Log-SqlcmdArgsSafe -Args $sqlArgs
& $SqlcmdExe @sqlArgs
if ($LASTEXITCODE -ne 0) {
Write-Log WARN "Grant BACKUP fallito su DB [$db] (sqlcmd ExitCode=$LASTEXITCODE)."
} else {
Write-Log INFO "Concessi BACKUP DATABASE/LOG a NT AUTHORITY\\SYSTEM su [$db]."
}
Remove-Item -LiteralPath $tmpSql -Force -ErrorAction SilentlyContinue
}
} catch {
Write-Log WARN "Errore durante concessione GRANT BACKUP a NT AUTHORITY\\SYSTEM: $_"
}
}
$names = @()
foreach ($line in @($res)) {
$n = ($line | ForEach-Object { $_.Trim() })
if ($n) { $names += $n }
@ -486,6 +526,7 @@ function Backup-SqlDatabases {
return $null
}
Write-Log INFO ("DB trovati: " + (@($dbList) -join ', '))
Ensure-BackupGrants-ForSystem -SqlcmdExe $sqlcmd -DbList $dbList
$bakPaths = @()
foreach ($db in @($dbList)) {