Advertisement
Guest User

Untitled

a guest
Apr 29th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.82 KB | None | 0 0
  1. # This script creates a copy of a database (minus data) on the same server
  2. # set "Option Explicit" to catch subtle errors
  3. set-psdebug -strict
  4. $servername='.' # server name and instance
  5. $servernameLabel=$servername;
  6. if ($servername -eq '.') {
  7. $servernameLabel = 'localhost';
  8. }
  9. $Database='CppeDB' # the database to copy from
  10. $ServerDirectory =$null # we let the script find a suitable place for data etc.
  11. #$DirectoryToSaveTo='C:\Temp\db'; # local directory to save build-scripts to
  12. $DirectoryToSaveTo=$PSScriptRoot + ''; # local directory to save build-scripts to
  13. $ErrorActionPreference = "stop" # you can opt to stagger on, bleeding, if an error occurs
  14.  
  15. Trap {
  16. # Handle the error
  17. $err = $_.Exception
  18. write-host $err.Message
  19. while( $err.InnerException ) {
  20. $err = $err.InnerException
  21. write-host $err.Message
  22. };
  23. # End the script.
  24. break
  25. }
  26. # Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries
  27. $v = [System.Reflection.Assembly]::LoadWithPartialName( 'Microsoft.SqlServer.SMO')
  28. if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {
  29. [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended') | out-null
  30. }
  31. $My='Microsoft.SqlServer.Management.Smo'
  32. $s = new-object ("$My.Server") $ServerName #get the server and find a good place for scripts etc.
  33. if ($s.Version -eq $null ){Throw "Can't find the instance $Datasource"}
  34. $db= $s.Databases[$Database]
  35. if ($db.name -ne $Database){Throw "Can't find the database '$Database' in $Datasource"};
  36. if ($ServerDirectory -eq $null) {$ServerDirectory=$s.RootDirectory+'\SCRIPTS\'}
  37. #get the name of the server etc for the directory where we store local build scripts
  38. $Server=$s.netname -replace '[\\\/\:\.]',' ' #remove characters that can cause problems
  39. $instance = $s.instanceName -replace '[\\\/\:\.]',' ' #ditto
  40. $DatabaseName =$database -replace '[\\\/\:\.]',' ' #ditto
  41. "Scripting Database Schema for '$Database'";
  42.  
  43. $DirectoryToSaveTo=$DirectoryToSaveTo+$Instance+'\' #database scripts are local on client
  44. if (!( Test-Path -path "$DirectoryToSaveTo" )) #create it if not existing
  45. {$progress ="attempting to create word directory $DirectoryToSaveTo"
  46. Try { New-Item "$DirectoryToSaveTo" -type directory | out-null }
  47. Catch [system.exceptio]{
  48. Write-Error "error while $progress. $_"
  49. return
  50. }
  51. }
  52. "Saving to '$DirectoryToSaveTo'";
  53. $SchemaFileName = "$($DirectoryToSaveTo)$($servernameLabel)_$($DatabaseName)_Schema.sql";
  54.  
  55. <# now we will use the canteen system of SMO to specify what we want from the script. It is best to have a list of the defaults to hand and just over-ride the defaults where necessary, but there is a chance that a later revision of SMO could change the defaults so beware! #>
  56. $CreationScriptOptions = new-object ("$My.ScriptingOptions")
  57. $CreationScriptOptions.ExtendedProperties= $true # yes we want these
  58. $CreationScriptOptions.DRIAll= $true # and all the constraints
  59. $CreationScriptOptions.Indexes= $true # Yup, these would be nice
  60. $CreationScriptOptions.Triggers= $true # This should be included when scripting a database
  61. $CreationScriptOptions.ScriptBatchTerminator = $true # this only goes to the file
  62. $CreationScriptOptions.Filename = $SchemaFileName;
  63. #we have to write to a file to get the GOs
  64. $CreationScriptOptions.IncludeHeaders = $true; #of course
  65. $CreationScriptOptions.ToFileOnly = $true #no need of string output as well
  66. $CreationScriptOptions.IncludeIfNotExists = $true #not necessary but it means the script can be more versatile
  67. $transfer = new-object ("$My.Transfer") $db
  68. $transfer.options=$CreationScriptOptions #tell the transfer object of pur preferences
  69. $scripter = new-object ("$My.Scripter") $s #script out the database creation
  70. $scripter.options=$CreationScriptOptions #with the same options
  71. $scripter.Script($db) #do it
  72. #now we alter the name to create the copy. This isn't safe with certain database names
  73.  
  74. # add the database object build script
  75. $transfer.options.AppendToFile=$true
  76. $transfer.options.ScriptDrops=$true
  77. $transfer.EnumScriptTransfer()
  78. $transfer.options.ScriptDrops=$false
  79. $transfer.EnumScriptTransfer()
  80. "Saved to "+$SchemaFileName+'!!'
  81. Trap [System.Data.SqlClient.SqlException] {
  82. Write-Host "A SQL Error occurred:`n" + $_.Exception.Message
  83. break
  84. }
  85. "Post-Processed Schema file completed."
  86. (Get-Content $SchemaFileName) |
  87. Foreach-Object {$_ -replace '\/\*\*\*\*\*\* Object:.*?\*\*\*\*\*\*\/',''} |
  88. Out-File $SchemaFileName
  89.  
  90. #Get-ChildItem -Path $SchemaFileName | % {
  91. # $text = ""
  92. # Get-Content $_.FullName | % {$text += $_ + "NEWLINE"}
  93. # #$text = $text.Replace("CONTAINMENT = NONE","/*CONTAINMENT = NONE").Replace("SQL_Latin1_General_CP1_CI_AS","SQL_Latin1_General_CP1_CI_AS*/", 1)
  94. # $text -replace '\/\*\*\*\*\*\* Object:.*?\*\*\*\*\*\*\/',''
  95. # $text.Replace("NEWLINE","`r`n") | Out-File $_.FullName -Force
  96. #}
  97.  
  98. "done!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement