0

我有一个 Powershell 函数,它从 SqlPs 模块调用“Restore-SqlDatabase”,并通过 splatting 向函数发送参数。我试图弄清楚为什么它没有按我期望的方式工作。这是我的代码:

$SqlParams = @{"ServerInstance"="'$ServerName'";
    "Database"="'$DatabaseName'";
    "BackupFile"="'$BackupFile'";}

if($Credential -ne $null) {
    $SqlParams.Add("SqlCredential", $Credential)
}

if($ReplaceDatabase) {
    $SqlParams.Add("ReplaceDatabase", $null)
}

try { $PathResult = Test-Path -Path $RestorePath } catch { $PathResult = $False }

if($PathResult) {
    Write-Verbose "RestorePath exists, using: $RestorePath"

    $RelocateData = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
    $RelocateData.LogicalFileName = $DatabaseName
    $RelocateData.PhysicalFileName = $(Join-Path -Path $RestorePath -ChildPath "$DatabaseName.mdf")

    $RelocateLog = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
    $RelocateLog.LogicalFileName = "$DatabaseName`_log"
    $RelocateLog.PhysicalFileName = $(Join-Path -Path $RestorePath -ChildPath "$DatabaseName`_log.ldf")

    $RelocateFile = @($RelocateData,$RelocateLog)
    $SqlParams.Add("RelocateFile", $RelocateFile)
}

try{
    Write-Verbose "Using the following parameters:"
    $paramString = $SqlParams | Out-String
    Write-Verbose $paramString 
    Restore-SqlDatabase @SqlParams
} catch { 
    Write-Error $_ 
    Write-Output "Restore failed..."
    return
}
Write-Output "Database successfully restored!"

当我运行它时,它无法连接到数据库。然而,当我直接在终端中运行命令时,使用“param”哈希表和相同的参数值,它完全按预期工作。

对我有什么建议吗?

4

1 回答 1

0

这里有一些秘密酱汁。

Restore-SqlDatabase在通话之前这样做:

SQLCMD -S $ServerName -d master -Q "Alter Database [$DatabaseName] SET SINGLE_USER With ROLLBACK IMMEDIATE"

并在Restore-SqlDatabase通话后这样做:

SQLCMD -S $ServerName -d master -Q "Alter Database [$DatabaseName] SET MULTI_USER WITH ROLLBACK IMMEDIATE"

现在一切似乎都很好。

于 2017-03-16T19:22:09.450 回答