Skip to content

Instantly share code, notes, and snippets.

@niphlod
Created November 28, 2017 17:16
Show Gist options
  • Save niphlod/c215935e656b4ddb7c74def6181321c9 to your computer and use it in GitHub Desktop.
Save niphlod/c215935e656b4ddb7c74def6181321c9 to your computer and use it in GitHub Desktop.
function help

Restore-DbaDatabase

SYNOPSIS

Restores a SQL Server Database from a set of backupfiles

SYNTAX

Restore-DbaDatabase -Path <Object[]> -SqlInstance <DbaInstanceParameter> [-SqlCredential <PSCredential>] [-DatabaseName <Object[]>] [-DestinationDataDirectory <String>] [-DestinationLogDirectory <String>] [-RestoreTime <DateTime>] [-NoRecovery] [-WithReplace] [-XpDirTree] [-OutputScriptOnly] [-VerifyOnly] [-MaintenanceSolutionBackup] [-FileMapping <Hashtable>] [-IgnoreLogBackup] [-useDestinationDefaultDirectories] [-ReuseSourceFolderStructure] [-DestinationFilePrefix <String>] 

[-RestoredDatababaseNamePrefix <String>] [-TrustDbBackupHistory] [-MaxTransferSize <Int32>] [-BlockSize <Int32>] [-BufferCount <Int32>] [-DirectoryRecurse] [-EnableException] [-StandbyDirectory <String>] [-Continue] [-AzureCredential <String>] [-ReplaceDbNameInFile] [-DestinationFileSuffix <String>] [-KeepCDC] [-AllowContinue] [-GetBackupInformation <String>] [-StopAfterGetBackupInformation] [-SelectBackupInformation <String>] [-StopAfterSelectBackupInformation] [-FormatBackupInformation 

<String>] [-StopAfterFormatBackupInformation] [-TestBackupInformation <String>] [-StopAfterTestBackupInformation] [-StatementTimeout <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>]



Restore-DbaDatabase -SqlInstance <DbaInstanceParameter> [-SqlCredential <PSCredential>] [-DatabaseName <Object[]>] [-OutputScriptOnly] [-EnableException] [-AzureCredential <String>] [-Recover] [-AllowContinue] [-GetBackupInformation <String>] [-StopAfterGetBackupInformation] [-SelectBackupInformation <String>] [-StopAfterSelectBackupInformation] [-FormatBackupInformation <String>] [-StopAfterFormatBackupInformation] [-TestBackupInformation <String>] [-StopAfterTestBackupInformation] 

[-StatementTimeout <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>]

DESCRIPTION

Upon being passed a list of potential backups files this command will scan the files, select those that contain SQL Server backup sets. It will then filter those files down to a set that can perform the requested restore, checking that we have a full restore chain to the point in time requested by the caller.

The function defaults to working on a remote instance. This means that all paths passed in must be relative to the remote instance. XpDirTree will be used to perform the file scans

Various means can be used to pass in a list of files to be considered. The default is to non recursively scan the folder passed in.

PARAMETERS

-Path <Object[]>

Path to SQL Server backup files.

Paths passed in as strings will be scanned using the desired method, default is a non recursive folder scan Accepts multiple paths separated by ','

Or it can consist of FileInfo objects, such as the output of Get-ChildItem or Get-Item. This allows you to work with your own filestructures as needed

Required?                    true
Position?                    named
Default value
Accept pipeline input?       true (ByValue)
Accept wildcard characters?  false

-SqlInstance <DbaInstanceParameter>

The SQL Server instance to restore to.

Required?                    true
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-SqlCredential <PSCredential>

Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted.

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-DatabaseName <Object[]>

Name to restore the database under. Only works with a single database restore. If multiple database are found in the provided paths then we will exit

Required?                    false
Position?                    named
Default value
Accept pipeline input?       true (ByValue)
Accept wildcard characters?  false

-DestinationDataDirectory <String>

Path to restore the SQL Server backups to on the target instance. If only this parameter is specified, then all database files (data and log) will be restored to this location

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-DestinationLogDirectory <String>

Path to restore the database log files to. This parameter can only be specified alongside DestinationDataDirectory.

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-RestoreTime <DateTime>

Specify a DateTime object to which you want the database restored to. Default is to the latest point available in the specified backups

Required?                    false
Position?                    named
Default value                (Get-Date).AddYears(1)
Accept pipeline input?       false
Accept wildcard characters?  false

-NoRecovery <SwitchParameter>

Indicates if the databases should be recovered after last restore. Default is to recover

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-WithReplace <SwitchParameter>

Switch indicated is the restore is allowed to replace an existing database.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-XpDirTree <SwitchParameter>

Switch that indicated file scanning should be performed by the SQL Server instance using xp_dirtree This will scan recursively from the passed in path You must have sysadmin role membership on the instance for this to work.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-OutputScriptOnly <SwitchParameter>

Switch indicates that ONLY T-SQL scripts should be generated, no restore takes place

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-VerifyOnly <SwitchParameter>

Switch indicate that restore should be verified

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-MaintenanceSolutionBackup <SwitchParameter>

Switch to indicate the backup files are in a folder structure as created by Ola Hallengreen's maintenance scripts. This swith enables a faster check for suitable backups. Other options require all files to be read first to ensure we have an anchoring full backup. Because we can rely on specific locations for backups performed with OlaHallengren's backup solution, we can rely on file locations.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-FileMapping <Hashtable>

A hashtable that can be used to move specific files to a location. $FileMapping = @{'DataFile1'='c:\restoredfiles\Datafile1.mdf';'DataFile3'='d:\DataFile3.mdf'} And files not specified in the mapping will be restored to their original location This Parameter is exclusive with DestinationDataDirectory

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-IgnoreLogBackup <SwitchParameter>

This switch tells the function to ignore transaction log backups. The process will restore to the latest full or differential backup point only

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-useDestinationDefaultDirectories <SwitchParameter>

Switch that tells the restore to use the default Data and Log locations on the target server. If they don't exist, the function will try to create them

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-ReuseSourceFolderStructure <SwitchParameter>

By default, databases will be migrated to the destination Sql Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. The same structure on the SOURCE will be kept exactly, so consider this if you're migrating between different versions and use part of Microsoft's default Sql structure (MSSql12.INSTANCE, etc)

*Note, to reuse destination folder structure, specify -WithReplace

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-DestinationFilePrefix <String>

This value will be prefixed to ALL restored files (log and data). This is just a simple string prefix. If you want to perform more complex rename operations then please use the FileMapping parameter

This will apply to all file move options, except for FileMapping

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-RestoredDatababaseNamePrefix <String>

A string which will be prefixed to the start of the restore Database's Name Useful if restoring a copy to the same sql server for testing.

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-TrustDbBackupHistory <SwitchParameter>

This switch can be used when piping the output of Get-DbaBackupHistory or Backup-DbaDatabase into this command. It allows the user to say that they trust that the output from those commands is correct, and skips the file header read portion of the process. This means a faster process, but at the risk of not knowing till halfway through the restore that something is wrong with a file.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-MaxTransferSize <Int32>

Parameter to set the unit of transfer. Values must be a multiple by 64kb

Required?                    false
Position?                    named
Default value                0
Accept pipeline input?       false
Accept wildcard characters?  false

-BlockSize <Int32>

Specifies the block size to use. Must be one of 0.5kb,1kb,2kb,4kb,8kb,16kb,32kb or 64kb Can be specified in bytes Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

Required?                    false
Position?                    named
Default value                0
Accept pipeline input?       false
Accept wildcard characters?  false

-BufferCount <Int32>

Number of I/O buffers to use to perform the operation. Refer to https://msdn.microsoft.com/en-us/library/ms178615.aspx for more detail

Required?                    false
Position?                    named
Default value                0
Accept pipeline input?       false
Accept wildcard characters?  false

-DirectoryRecurse <SwitchParameter>

If specified the specified directory will be recursed into

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-EnableException <SwitchParameter>

By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-StandbyDirectory <String>

If a directory is specified the database(s) will be restored into a standby state, with the standby file placed into this directory (which must exist, and be writable by the target Sql Server instance)

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-Continue <SwitchParameter>

If specified we will to attempt to recover more transaction log backups onto database(s) in Recovering or Standby states

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-AzureCredential <String>

The name of the SQL Server credential to be used if restoring from an Azure hosted backup

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-ReplaceDbNameInFile <SwitchParameter>

If switch set and occurence of the original database's name in a data or log file will be replace with the name specified in the Databasename paramter

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-DestinationFileSuffix <String>

This value will be suffixed to ALL restored files (log and data). This is just a simple string suffix. If you want to perform more complex rename operations then please use the FileMapping parameter

This will apply to all file move options, except for FileMapping

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-Recover <SwitchParameter>

If set will perform recovery on the indicated database

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-KeepCDC <SwitchParameter>

Indicates whether CDC information should be restored as part of the database

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-AllowContinue <SwitchParameter>

By default, Restore-DbaDatabase will stop restoring any databases if it comes across an error. Use this switch to enable it to restore all databases without issues.

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-GetBackupInformation <String>

Passing a string value into this parameter will cause a global variable to be created holding the output of Get-DbaBackupInformation

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-StopAfterGetBackupInformation <SwitchParameter>

Switch which will cause the function to exit after returning GetBackupInformation

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-SelectBackupInformation <String>

Passing a string value into this parameter will cause a global variable to be created holding the output of Select-DbaBackupInformation

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-StopAfterSelectBackupInformation <SwitchParameter>

Switch which will cause the function to exit after returning SelectBackupInformation

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-FormatBackupInformation <String>

Passing a string value into this parameter will cause a global variable to be created holding the output of Format-DbaBackupInformation

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-StopAfterFormatBackupInformation <SwitchParameter>

Switch which will cause the function to exit after returning FormatBackupInformation

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-TestBackupInformation <String>

Passing a string value into this parameter will cause a global variable to be created holding the output of Test-DbaBackupInformation

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-StopAfterTestBackupInformation <SwitchParameter>

Switch which will cause the function to exit after returning TestBackupInformation

Required?                    false
Position?                    named
Default value                False
Accept pipeline input?       false
Accept wildcard characters?  false

-StatementTimeout <Int32>

Timeout in minutes. Defaults to infinity (restores can take a while.)

Required?                    false
Position?                    named
Default value                0
Accept pipeline input?       false
Accept wildcard characters?  false

-WhatIf <SwitchParameter>

Shows what would happen if the command would execute, but does not actually perform the command

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

-Confirm <SwitchParameter>

Prompts to confirm certain actions

Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false

INPUTS

NOTES

Tags: DisasterRecovery, Backup, Restore Author: Stuart Moore (@napalmgram), stuart-moore.com

dbatools PowerShell module (https://dbatools.io, clemaire@gmail.com) Copyright (C) 2016 Chrissy LeMaire License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0

EXAMPLES

EXAMPLE 1

PS C:\>Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups

Scans all the backup files in \\server2\backups, filters them and restores the database to server1\instance1

EXAMPLE 2

PS C:\>Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\restores

Scans all the backup files in \\server2\backups$ stored in an Ola Hallengren style folder structure,
filters them and restores the database to the c:\restores folder on server1\instance1

EXAMPLE 3

PS C:\>Get-ChildItem c:\SQLbackups1\, \\server\sqlbackups2 | Restore-DbaDatabase -SqlInstance server1\instance1

Takes the provided files from multiple directories and restores them on  server1\instance1

EXAMPLE 4

PS C:\>$RestoreTime = Get-Date('11:19 23/12/2016')

Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -MaintenanceSolutionBackup -DestinationDataDirectory c:\restores -RestoreTime $RestoreTime

Scans all the backup files in \\server2\backups stored in an Ola Hallengren style folder structure,
filters them and restores the database to the c:\restores folder on server1\instance1 up to 11:19 23/12/2016

EXAMPLE 5

PS C:\>Restore-DbaDatabase -SqlInstance server1\instance1 -Path \\server2\backups -DestinationDataDirectory c:\restores -OutputScriptOnly | Select-Object -ExpandProperty Tsql | Out-File -Filepath c:\scripts\restore.sql

Scans all the backup files in \\server2\backups stored in an Ola Hallengren style folder structure,
filters them and generate the T-SQL Scripts to restore the database to the latest point in time,
and then stores the output in a file for later retrieval

EXAMPLE 6

PS C:\>Restore-DbaDatabase -SqlInstance server1\instance1 -Path c:\backups -DestinationDataDirectory c:\DataFiles -DestinationLogDirectory c:\LogFile

Scans all the files in c:\backups and then restores them onto the SQL Server Instance server1\instance1, placing data files
c:\DataFiles and all the log files into c:\LogFiles

EXAMPLE 7

PS C:\>Restore-DbaDatabase -SqlInstance server1\instance1 -Path http://demo.blob.core.windows.net/backups/dbbackup.bak -AzureCredential MyAzureCredential

Will restore the backup held at  http://demo.blob.core.windows.net/backups/dbbackup.bak to server1\instance1. The connection to Azure will be made using the 
credential MyAzureCredential held on instance Server1\instance1

EXAMPLE 8

PS C:\>$File = Get-ChildItem c:\backups, \\server1\backups -recurse

$File | Restore-DbaDatabase -SqlInstance Server1\Instance -useDestinationDefaultDirectories

This will take all of the files found under the folders c:\backups and \\server1\backups, and pipeline them into
Restore-DbaDatabase. Restore-DbaDatabase will then scan all of the files, and restore all of the databases included
to the latest point in time covered by their backups. All data and log files will be moved to the default SQL Server
folder for those file types as defined on the target instance.

EXAMPLE 9

PS C:\>$files = Get-ChildItem C:\dbatools\db1

#Restore database to a point in time
$files | Restore-DbaDatabase -SqlInstance server\instance1 `
			-DestinationFilePrefix prefix -DatabaseName Restored  `
			-RestoreTime (get-date "14:58:30 22/05/2017") `
			-NoRecovery -WithReplace -StandbyDirectory C:\dbatools\standby 

#It's in standby so we can peek at it
Invoke-Sqlcmd2 -ServerInstance server\instance1 -Query "select top 1 * from Restored.dbo.steps order by dt desc"

#Not quite there so let's roll on a bit:
$files | Restore-DbaDatabase -SqlInstance server\instance1 `
			-DestinationFilePrefix prefix -DatabaseName Restored `
			-continue -WithReplace -RestoreTime (get-date "15:09:30 22/05/2017") `
			-StandbyDirectory C:\dbatools\standby

Invoke-Sqlcmd2 -ServerInstance server\instance1 -Query "select top 1 * from restored.dbo.steps order by dt desc"

Restore-DbaDatabase -SqlInstance server\instance1 `
			-DestinationFilePrefix prefix -DatabaseName Restored `
			-continue -WithReplace 

In this example we step through the backup files held in c:\dbatools\db1 folder.
First we restore the database to a point in time in standby mode. This means we can check some details in the databases
We then roll it on a further 9 minutes to perform some more checks
And finally we continue by rolling it all the way forward to the latest point in the backup.
At each step, only the log files needed to roll the database forward are restored.

EXAMPLE 10

PS C:\>Restore-DbaDatabase -SqlInstance server\instance1 -Path c:\backups -DatabaseName example1 -WithNoRecovery

Restore-DbaDatabase -SqlInstance server\instance1 -Recover -DatabaseName example1

EXAMPLE 11

PS C:\>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment