Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

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.

  1. Open PowerShell ISE as administrator.

  2. 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...