Home > Software design >  How can I get the backed-up Database name?
How can I get the backed-up Database name?

Time:01-07

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?

CodePudding user response:

$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
 }

CodePudding user response:

In PowerShell Pipelines you can use $_ (alias of $PSItem) to access piped variables, so you should be able to use $_.Name to get the name of the database you selected with Out-GridView.

Example: (Might not work since I don't personally use PS)

$date = Get-Date -format "yyyyMMdd_hhmmssfff"
Get-SqlDatabase -ServerInstance localhost | Out-GridView -PassThru | Backup-SqlDatabase -BackupFile "C:\Backup\$($_.Name)_$date.bak"
  • Related