我有一个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”哈希表和相同的参数值,它完全按预期工作。
给我的任何提示?
答案 0 :(得分: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"
现在一切似乎都很好。