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

Detaching a database


In this recipe, we will detach a database programmatically.

Getting ready

For the purpose of this recipe, let's create a database called TestDB and put its data files in the C:\DATA folder. Open up SQL Server Management Studio and run the following code:

IF DB_ID('TestDB') IS NOT NULL
DROP DATABASE TestDB
GO

CREATE DATABASE [TestDB]
 CONTAINMENT = NONE
 ON  PRIMARY
( NAME = N'TestDB', FILENAME = N'C:\DATA\TestDB.mdf' , SIZE = 4096KB , FILEGROWTH = 1024KB ),
 FILEGROUP [FG1]
( NAME = N'data1', FILENAME = N'C:\DATA\data1.ndf' , SIZE = 4096KB , FILEGROWTH = 1024KB ),
 FILEGROUP [FG2]
( NAME = N'data2', FILENAME = N'C:\DATA\data2.ndf' , SIZE = 4096KB , FILEGROWTH = 1024KB )
 LOG ON
( NAME = N'TestDB_log', FILENAME = N'C:\DATA\TestDB_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
GO

How to do it...

To detach a database programmatically, follow these steps:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module and create a new SMO Server object:

    #import SQL Server module
    Import...