Best script to restore multiple databases with SQL Server 2012?

前端 未结 5 527
悲&欢浪女
悲&欢浪女 2021-02-06 10:29

I have to restore around 60 SQL databases of different sizes. I googled to find a script to restore all databases after each other , just picking it 1 by 1 from my folder. I was

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-06 10:58

    The following Powershell script worked best for me.

    Source: Simon Osborne's SQL Blog

    $backupRoot = Get-ChildItem -Path "D:\BAK_FILE_FOLDER"
    $datafilesDest = "D:\DATA_FILE_FOLDER"
    $logfilesDest = "D:\LOG_FILE_FOLDER"
    $server = "server\inst" 
    
    ## For each folder in the backup root directory...
    #
    foreach($folder in $backupRoot)
    {   
        # Get the most recent .bak files for all databases...
        $backupFiles = Get-ChildItem -Path $folder.FullName -Filter "*.bak" -Recurse | Sort-Object -Property CreationTime -Descending | Select-Object -First 1
    
    
        # For each .bak file...
        foreach ($backupFile in $backupFiles)
        {
            # Restore the header to get the database name...
            $query = "RESTORE HEADERONLY FROM DISK = N'"+$backupFile.FullName+"'"
            $headerInfo = Invoke-Sqlcmd -ServerInstance $server -Query $query
            $databaseName = $headerInfo.DatabaseName
    
            # Restore the file list to get the logical filenames of the database files...
            $query = "RESTORE FILELISTONLY FROM DISK = N'"+$backupFile.FullName+"'"
            $files = Invoke-Sqlcmd -ServerInstance $server -Query $query
    
            # Differentiate data files from log files...
            $dataFile = $files | Where-Object -Property Type -EQ "D"
            $logFile = $files | Where-Object -Property Type -EQ "L"
    
            # Set some variables...
            $dataFileName = $dataFile.LogicalName
            $logFileName = $logFile.LogicalName
    
            # Set the destination of the restored files...
            $dataFileFullPath = $datafilesDest+"\"+$dataFileName+".mdf"
            $logFileFullPath = $logfilesDest+"\"+$logFileName+".ldf"
    
            # Create some "Relocate" file objects to pass to the Restore-SqlDatabase cmdlet...
            $RelocateData = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList $dataFileName, $dataFileFullPath
            $RelocateLog = New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' -ArgumentList $logFileName, $logFileFullPath
    
            # Perform the database restore... and then go around the loop.
            Restore-SqlDatabase -ServerInstance $server -Database $databaseName -BackupFile $backupFile.FullName -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase
        }
    } 
    

提交回复
热议问题