SQL Clone 3

Help for older versions available.

Create an image for the latest backup

One key use case for SQL Clone is to have the latest possible copy of a production database available for quick mounting in another environment.

For a backup file matching a database name, this script obtains the latest then uses it to create a SQL Clone image.

You need to provide a SQL Clone Agent to perform the operation, but you only need the disk space for the database to be available in the final destination (the operation uses a virtual mount point into that location).

  1. # Script to create a new SQL Clone data image from a backup file
  2.  
  3. $SQLCloneServer= 'http://sql-clone.example.com:14145'
  4. $TemporaryServerMachine = 'wks-dev1' # Specifies which instance of SQL Server will be temporarily used to restore the backup while creating an image
  5. $TemporaryServerInstance = 'sql2014' # No additional disk space is required for this temporary restore
  6.  
  7. Connect-SqlClone -ServerUrl $SQLCloneServer
  8.  
  9. $TemporaryServer = Get-SqlCloneSqlServerInstance -MachineName $TemporaryServerMachine -InstanceName $TemporaryServerInstance # You can omit the instance parameter if there is only one instance
  10.  
  11. $SourceDatabase = 'Forex'
  12. $BackupFolder = '\\File1.example.com\Backups\SQL\MSSQL\Backup'
  13.  
  14. if (!(Test-Path ($BackupFolder)))
  15. {
  16. write-host 'Backup folder not found. Exiting.'
  17. break
  18. }
  19.  
  20. # Get the latest backup file for our database (striped backups would be more complex)
  21. $BackupFiles = Get-ChildItem -Path $BackupFolder |
  22. Where-Object -FilterScript { $_.Name.Substring(0,$SourceDatabase.Length) -eq $SourceDatabase} # My backup files always start with the database name
  23.  
  24. # Now we have a filtered list, sort to get latest
  25. $BackupFile = $BackupFiles |
  26. Sort-Object -Property LastWriteTime |
  27. Select-Object -Last 1 # I only want the most recent file for this database to be used
  28.  
  29. $BackupFileName = $BackupFile.FullName
  30.  
  31. #Start a timer
  32. $elapsed = [System.Diagnostics.Stopwatch]::StartNew()
  33.  
  34. "Started at {0}, creating data image for database ""{1}"" from backup file ""{2}""" -f $(get-date) , $SourceDatabase , $BackupFileName
  35.  
  36. $DataImageName = $SourceDatabase + "_" + (Get-Date -Format "yyyyMMdd") # Prepare a name for the data image, with a timestamp
  37. $ImageDestination = Get-SqlCloneImageLocation -Path '\\filestore.example.com\SQLClone\SQL Clone Images' # Point to the file share we want to use to store the image
  38.  
  39. $NewImage = New-SqlCloneImage -Name $DataImageName -SqlServerInstance $TemporaryServer -BackupFileName $BackupFileName -Destination $ImageDestination | Wait-SqlCloneOperation # Create the data image and wait for completion
  40.  
  41. "Total Elapsed Time: {0}" -f $($elapsed.Elapsed.ToString())

Didn't find what you were looking for?