Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SQL Server 2014 with Powershell v5 Cookbook

You're reading from   SQL Server 2014 with Powershell v5 Cookbook Over 150 real-world recipes to simplify database management, automate repetitive tasks, and enhance your productivity

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher Packt
ISBN-13 9781785283321
Length 760 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Donabel Santos Donabel Santos
Author Profile Icon Donabel Santos
Donabel Santos
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Getting Started with SQL Server and PowerShell 2. SQL Server and PowerShell Basic Tasks FREE CHAPTER 3. Basic Administration 4. Security 5. Backup and Restore 6. Advanced Administration 7. Audit and Policies 8. High Availability with AlwaysOn 9. SQL Server Development 10. Business Intelligence 11. Helpful PowerShell Snippets A. PowerShell Primer B. Creating a SQL Server VM 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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image