Copying a database
In this recipe, we will look at how to copy a database using PowerShell and SMO.
Getting ready
In this recipe, we will assume you have the TestDB
database already created from previous recipes. If you do not have it, you can also substitute this with any database you already have in your instance.
How to do it...
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
Import the
SQLPS
module and create a new SMO Server object, as follows:#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run:
$databasename = "TestDB" $sourcedatabase = $server.Databases[$databasename] #Create a database to hold the copy of your database $dbnamecopy = "$($databasename)_copy" $dbcopy = New-Object -TypeName Microsoft.SqlServer.Management...