使用PowerShell在远程SQL Server中还原数据库

时间:2018-03-13 13:48:09

标签: powershell powershell-v4.0

我正在恢复本地服务器上的数据库备份并在远程SQL服务器中恢复。我看到一个错误

  

"异常调用" SqlRestore"用" 1"参数:"恢复失败   对于Server server \ instance at line:74 char:5"

不确定问题出在哪里。请参阅下面的代码。

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum") | Out-Null

if($useSqlServerAuthentication)
{

    $passwordSecureString = ConvertTo-SecureString -String $pwd -AsPlainText -Force;
    $serverConnection = new-object Microsoft.SqlServer.Management.Common.ServerConnection $SR, $user, $passwordSecureString;
    $smoserver = new-object Microsoft.SqlServer.Management.Smo.Server $serverConnection;
}
else
{
    $smoserver = new-object Microsoft.SqlServer.Management.Smo.Server $SR;
    write-host $smoserver
}

$dataFolder = $smoserver.Settings.DefaultFile;
$logFolder = $smoserver.Settings.DefaultLog;

if ($dataFolder.Length -eq 0)
{
    $dataFolder = $smoserver.Information.MasterDBPath;
}
if ($logFolder.Length -eq 0) 
{
    $logFolder = $smoserver.Information.MasterDBLogPath;
}

$backupDeviceItem = new-object Microsoft.SqlServer.Management.Smo.BackupDeviceItem $restorefile, 'File';
$restore = new-object 'Microsoft.SqlServer.Management.Smo.Restore';
$restore.Database = $Db;
$restore.Devices.Add($backupDeviceItem);

$dataFileNumber = 0;

foreach ($file in $restore.ReadFileList($server)) 
{
    $relocateFile = new-object 'Microsoft.SqlServer.Management.Smo.RelocateFile';
    $relocateFile.LogicalFileName = $file.LogicalName;
    if ($file.Type -eq 'D')
    {
        if($dataFileNumber -ge 1) { $suffix = "_$dataFileNumber"; }
        else { $suffix = $null; }
        $relocateFile.PhysicalFileName = "$dataFolder$DB.mdf";
        $dataFileNumber ++;
    }
    else 
    {
        $relocateFile.PhysicalFileName = "$logFolder\$DatabaseName$suffix.ldf";
    }
    $restore.RelocateFiles.Add($relocateFile) | out-null;
}    
$restore.SqlRestore($smoserver)

0 个答案:

没有答案