How can I get the backed-up Database name?

93 views Asked by At

I try to backup multiple SQL Server databases using this code:

$date = Get-Date -format "yyyyMMdd_hhmmssfff"
Get-SqlDatabase -ServerInstance localhost | Out-GridView -PassThru | Backup-SqlDatabase -BackupFile C:\Backup\MyBackup_$date.bak

I'm able to combine the backup time in the backup file ($date), but not the name of the database, and as a consequence - I get only one backup file because each one overrides the previous one (this code enables me to select multiple databases from a pop up list). How can I get the database name in order to combine it in the bak file?

1

There are 1 answers

0
Geri Reshef On
$MyServer = "localhost" 
$DBs = Get-SqlDatabase -ServerInstance $MyServer | Out-GridView -OutputMode Multiple
foreach ($DB in $DBs) {
$dbName = $DB.Name
Write-Host $dbName
$date = Get-Date -format "yyyyMMdd_hhmmss"
Backup-SqlDatabase -ServerInstance $MyServer -Database $dbName -BackupFile C:\Backup\$MyServer-$dbName-$date.bak
 }