File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -870,6 +870,21 @@ function Backup-DbaDatabase {
870870 $FinalBackupPath [0 ] = $FinalBackupPath [0 ] + $slash + $BackupFinalName
871871 }
872872
873+ # Auto-detect dbname token to prevent duplication when using CreateFolder + ReplaceInName
874+ if ($CreateFolder -and $ReplaceInName -and -not $NoAppendDbNameInPath ) {
875+ $containsDbNameToken = $false
876+ foreach ($pathToCheck in $FinalBackupPath ) {
877+ if ($pathToCheck -match " \bdbname\b" ) {
878+ $containsDbNameToken = $true
879+ break
880+ }
881+ }
882+ if ($containsDbNameToken ) {
883+ Write-Message - Level Verbose - Message " Path contains 'dbname' token with ReplaceInName. Automatically skipping database folder creation to prevent duplication."
884+ $NoAppendDbNameInPath = $true
885+ }
886+ }
887+
873888 if ($CreateFolder -and $FinalBackupPath [0 ] -ne ' NUL:' ) {
874889 for ($i = 0 ; $i -lt $FinalBackupPath.Count ; $i ++ ) {
875890 $parent = [IO.Path ]::GetDirectoryName($FinalBackupPath [$i ])
Original file line number Diff line number Diff line change 485485 }
486486 }
487487
488+ Context " Test CreateFolder with ReplaceInName prevents duplicate dbname (issue 9135)" {
489+ It " Should not duplicate database name when path contains dbname token" {
490+ $results = Backup-DbaDatabase - SqlInstance $TestConfig.InstanceCopy1 - Database master - Path " $DestBackupDir \servername\instancename\dbname\backuptype" - BackupFileName " servername_dbname_backuptype_timestamp.bak" - ReplaceInName - CreateFolder - BuildPath
491+ $instanceName = ([DbaInstanceParameter ]$TestConfig.InstanceCopy1 ).InstanceName
492+ $serverName = ([DbaInstanceParameter ]$TestConfig.InstanceCopy1 ).ComputerName
493+ $results.BackupPath | Should - BeLike " $DestBackupDir \$serverName \$instanceName \master\Full\*"
494+ $results.BackupPath | Should -Not - BeLike " *\master\master\*"
495+ }
496+ }
497+
488498 Context " Test Backup Encryption with Certificate" {
489499 # TODO: Should the master key be created at lab startup like in instance3?
490500 BeforeAll {
You can’t perform that action at this time.
0 commit comments