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 create a copy of the database TestDB
and call it TestDB_Copy
. 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...
Let's list the steps required to copy a database using PowerShell.
Open PowerShell ISE as administrator.
Import the SQLPS module and create a new SMO Server object:
#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "localhost" $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...