Skip to content

Commit 23b429b

Browse files
Backup-DbaDatabase: Prevent duplicate dbname when using CreateFolder with ReplaceInName (#10224)
1 parent 902f23b commit 23b429b

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

public/Backup-DbaDatabase.ps1

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff 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])

tests/Backup-DbaDatabase.Tests.ps1

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,16 @@ go
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 {

0 commit comments

Comments
 (0)