Skip to content

Instantly share code, notes, and snippets.

@MikeFal
Last active August 3, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeFal/8cfa798d7dc423231abc3609ff213c0d to your computer and use it in GitHub Desktop.
Save MikeFal/8cfa798d7dc423231abc3609ff213c0d to your computer and use it in GitHub Desktop.
$relocate = @()
$file = Get-ChildItem C:\Temp\WideWorldImporters.bak
$dbname = (Invoke-Sqlcmd -ServerInstance localhost -Database tempdb -Query "RESTORE HEADERONLY FROM DISK='$($file.FullName)';").DatabaseName
$dbfiles = Invoke-Sqlcmd -ServerInstance localhost -Database tempdb -Query "RESTORE FILELISTONLY FROM DISK='$($file.FullName)';"
foreach($dbfile in $dbfiles){
if($dbfile.Type -eq 'L'){
$newfile = Join-Path -Path 'E:\SQLServer\Log' -ChildPath $($dbfile.PhysicalName.SubString($dbfile.PhysicalName.LastIndexOf('\')))
} else {
$newfile = Join-Path -Path 'E:\SQLServer\Data' -ChildPath $($dbfile.PhysicalName.SubString($dbfile.PhysicalName.LastIndexOf('\')))
}
$relocate += New-Object Microsoft.SqlServer.Management.Smo.RelocateFile ($dbfile.LogicalName,$newfile)
}
Restore-SqlDatabase -ServerInstance localhost -Database $dbname -RelocateFile $relocate -NoRecovery -BackupFile "$($file.FullName)" -RestoreAction Database -Script | Out-File C:\Temp\FullRestore.sql -Append
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment