Skip to content

Commit a6b1bf6

Browse files
Restore-DbaDatabase - Fix ReplaceDbNameInFile to only replace filename, not directory path (#9873)
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
1 parent 38e57e4 commit a6b1bf6

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

public/Format-DbaBackupInformation.ps1

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,14 @@ function Format-DbaBackupInformation {
186186
$_.PhysicalName = $FileMapping[$_.LogicalName]
187187
}
188188
} else {
189-
if ($ReplaceDbNameInFile -eq $true) {
190-
$_.PhysicalName = $_.PhysicalName -Replace $History.OriginalDatabase, $History.Database
191-
}
192189
Write-Message -Message " 1 PhysicalName = $($_.PhysicalName) " -Level Verbose
193190
$Pname = [System.Io.FileInfo]$_.PhysicalName
194191
$RestoreDir = $Pname.DirectoryName
195192
# Handle MacOS returning full path for BaseName
196193
$baseName = $Pname.BaseName.Split($PathSep)[-1]
194+
if ($ReplaceDbNameInFile -eq $true) {
195+
$baseName = $baseName -Replace $History.OriginalDatabase, $History.Database
196+
}
197197
if ($_.Type -eq 'D' -or $_.FileType -eq 'D') {
198198
if ('' -ne $DataFileDirectory) {
199199
$RestoreDir = $DataFileDirectory

tests/Restore-DbaDatabase.Tests.ps1

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,24 @@ Describe $CommandName -Tag IntegrationTests {
221221
}
222222

223223

224+
Context "ReplaceDbNameInFile regression test for #9656" {
225+
BeforeAll {
226+
$null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -ExcludeSystem -EnableException | Remove-DbaDatabase -EnableException
227+
}
228+
229+
It "Should replace database name in file basename only, not in directory path" {
230+
$scriptOutput = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName "NewDatabaseName" -ReplaceDbNameInFile -WithReplace -OutputScriptOnly
231+
$scriptOutput | Should -BeLike "*NewDatabaseName*"
232+
$scriptOutput | Should -Not -BeLike "*singlerestore\NewDatabaseName\*"
233+
}
234+
235+
It "Should generate valid MOVE statements with replaced database name" {
236+
$scriptOutput = Restore-DbaDatabase -SqlInstance $TestConfig.instance2 -Path "$($TestConfig.appveyorlabrepo)\singlerestore\singlerestore.bak" -DatabaseName "ReplacedDbName" -ReplaceDbNameInFile -WithReplace -OutputScriptOnly
237+
$scriptOutput | Should -Match "MOVE.*ReplacedDbName"
238+
}
239+
}
240+
241+
224242
Context "Test restoring as other login #6992" {
225243
BeforeAll {
226244
$null = Get-DbaDatabase -SqlInstance $TestConfig.instance2 -ExcludeSystem -EnableException | Remove-DbaDatabase -EnableException

0 commit comments

Comments
 (0)